I would like to write a template function which accepts 2 values and a functor or a lambda. The function calls the functor with those values and returns the result.
You're nearly there; just use decltype
:
template
auto Apply(T x, T y, Fn fn) -> decltype(fn(x, y))
{
return fn(x, y);
}
You could use std::result_of
(Difference between std::result_of and decltype) but why bother?
template
typename std::result_of::type Apply(T x, T y, Fn fn)
{
return fn(x, y);
}
Regarding the follow-up question: for a function
auto fn() -> { return ; }
substituting return-type
with decltype(
will usually work, but can be error prone. For example, consider:
auto f(char c) -> decltype(std::string() += c) { return std::string() += c; }
Here decltype
will yield std::string &
and your function will return an lvalue reference to a local! This would have to be changed to:
auto f(char c) -> std::remove_reference::type {
return std::string() += c;
}
In other cases,
could yield a value that is not returnable for reason of being e.g. noncopyable, containing a lambda, etc.