Decltype type for class type

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

It works:

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 link to the default constructor of the Foo class, which cannot be defined in some cases. Is there any way to do this without explicitly invoking any constructor?

+7
c ++ decltype
source share
2 answers

Yes there is. std::declval was introduced precisely for this reason (no need to rely on a specific constructor):

 decltype(std::declval<Foo>().get_value()) value; 
+9
source share

You can do this with std::declval , as shown below:

 #include <iostream> #include <utility> struct test { int val = 10; }; class Foo { public: test get_value() { return test(); } }; class Bar { public: using type = decltype(std::declval<Foo>().get_value()); }; int main() { Bar::type v; std::cout << v.val << std::endl; } 

Live demo

std::declval<T> converts any type T to a reference type, allowing you to use member functions in decltype expressions without having to go through constructors.

std::declval usually used in templates where valid template parameters may not have a common constructor but have the same member function whose return type is needed.

+3
source share

All Articles