Anonymous Entity
Anonymous Entity

Reputation: 3350

deducing return type to be type of template arguments method

It's hard for me to explain in English exactly what I mean, but the following non-compilable code might illustrate what I'm after:

template<class T>
auto fn(T t) -> decltype(T::method_call())
{
    return t.method_call();
}

Basically I want the function to return whatever it is T's method returns. What's the syntax to achieve this?

Upvotes: 0

Views: 46

Answers (1)

mpark
mpark

Reputation: 7904

In C++14, you can use deduced return type to simply say:

template <typename T>
decltype(auto) fn(T t) { return t.method_call(); }

You can also use the trailing return type to specify the same thing:

template <typename T>
auto fn(T t) -> decltype(t.method_call()) { return t.method_call(); }

Upvotes: 2

Related Questions