Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c++ - Function template return type deduction

I have some class C with const and non-const getters for some generic type Node:

template <typename NodeType>
class CParent{};

class Node {};

class C : public CParent<Node> {
    Node&       getNode(Index i);
    const Node& getNode(Index i) const;
};

Now I want to create an alias function that call getNode for an object of class C:

template <class CType>
NodeType& AliasGetNode(CType* cobject);

But how do I deduce NodeType? i.e., if I call AliasGetNode<const C>(c) and AliasGetNode<C>(c), NodeTypeshould be respectively const Node&and Node&.

How can I do this?

I tried the result_of and decltype approaches but have not been successful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let the compiler deduce the return type (as of C++14):

template <class CType>
decltype(auto) AliasGetNode(CType& cobject)
{
    return cobject.getNode(0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...