Reputation: 979
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?
Upvotes: 9
Views: 4965
Reputation: 55395
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;
Upvotes: 14
Reputation: 42899
You could do it with the help of std::declval
like the example 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;
}
std::declval<T>
converts any type T to a reference type, making it possible to use member functions in decltype
expressions without the need to go through constructors.
std::declval
is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed.
Upvotes: 5