Search code examples
c++decltype

decltype for class method type


I would like to store return value of class member function in another class.

This seems to work:

class Foo
{
public: 
   Foo(int) {} //non default constructor that hides default constructor
   unspecified_return_type get_value();


};

class Bar
{
    // stores a value returned by Foo::get_value
    decltype(Foo().get_value()) value;
};

However there is a reference to default constructor of class Foo, which may not be defined in some cases. Is there any way to do it without explicitly referring to any constructor?


Solution

  • Yup, there is. std::declval was introduced for exactly this reason (not needing to rely on a particular constructor):

    decltype(std::declval<Foo>().get_value()) value;