Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
manatttta Avatar asked Jan 02 '17 12:01

manatttta


2 Answers

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

template <class CType>
decltype(auto) AliasGetNode(CType& cobject)
{
    return cobject.getNode(0);
}
like image 82
Micha Wiedenmann Avatar answered Oct 25 '22 01:10

Micha Wiedenmann


I would recommend the:

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

This should fairly work since c++11

like image 30
W.F. Avatar answered Oct 25 '22 03:10

W.F.