How to deduce the type of the functor's return value?

Viewed 1953

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.

template <typename T, typename Fn> 
_ReturnTypeOfPred_ Apply(T x, T y, Fn fn)
  {
  return fn(x, y);
  }

Question: How can I define the return type of Apply to become equal to the return type of Fn? It is not necessarily equal to T, as in this example of the functor

template <typename T> 
auto Sum(T x, T y) -> decltype(x+y)
  {
  return x+y;
  }

Update

The 1st example was oversimplified. Should this one work?

template <typename TContainer, typename Fn> 
auto Apply(const TContainer& x, const TContainer& y, Fn fn) -> decltype(fn(x.front(), y.front()))
  {
  return fn(x.front(), y.front());
  }

Would it always work if I repeat return expression in decltype of the return type? Is there a more elegant way?

1 Answers
Related