Qwertypal
Qwertypal

Reputation: 189

Return value type for class member function

I have a couple of A like classes with method, say, get_value(), which return values of different types. And one class B, which returns a value with method value(). For example:

struct A_like1 {
    int get_value() const { return 10; }
};
struct A_like2 {
    char get_value() const { return 'a'; }
};
struct B
{
    float value() const { return 2.5; }
};

Now, I need a function to retrieve that value for these classes. I have a function:

template<typename T>
auto get_value(const T & t) -> result_of<decltype(&T::get_value)(T)>::type
{
    return t.get_value();
}

It gives me a number of compilation errors on VS2010 starting with:

Error   1   error C2061: syntax error : identifier 'type'   c:\_data\work\vmxi\c++\vox\vox\template_specialization.h    51

For B I have an overload, which works fine. The question is, how to make get_value() work with result_of<>()?

P.S. Hmm, I have just realized that I could've used -> decltype(T().get_value()) instead, which works fine. But why doesn't result_of<>() work? Besides, I was able to declare a variable in .cpp file:

result_of<decltype(&A_like1::get_value)(A_like1)>::type i=0;

Upvotes: 0

Views: 2264

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29072

The keyword typename can be used to declare that a dependent name, like std::result_of<T>::type, is a type. Otherwise, I believe it's assumed that std::result_of<T>::type is a data member. In C++14, several type traits have gotten a using alias that includes the typename keyword for you. These alias are always have the same name as the trait, with a _t suffix.

Try :

typename result_of<decltype(&T::get_value)(T)>::type

or, with C++14 :

result_of_t<decltype(&T::get_value)(T)>

Upvotes: 1

Related Questions