Jersey
Jersey

Reputation: 433

Deduce return type of a function template from argument types (not from arguments)

I am aware of the very straightforward usage of decltype, as in

template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(elem)) 
{
    return func(elem);
}   

I would like to know whether return type of a function can be deduced without reference to the function arguments, but instead to the argument type, i.e. something akin to decltype(func, T)?

I understand that in this case one is a type and the other is an object, but what I'm trying to do seems to be very natural. Yet I failed to find a simple way of expressing what I want. Any help?

Thank you.

Upvotes: 1

Views: 48

Answers (1)

Quentin
Quentin

Reputation: 63114

This is exactly what std::declval is for:

template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(std::declval<T>())) 
{
    return func(elem);
}

But since you do have an object of that type already, why bother?

Upvotes: 4

Related Questions