Micha Wiedenmann
Micha Wiedenmann

Reputation: 20823

How to deduce the return type of a function template base on a "function like" parameter?

Consider the following function template:

template<typename A, typename B, typename Op>
B Apply(A a, Op f)
{
    return f(a);
}

To use it, one has to explicitly specify the template parameters:

auto y = Apply<int, std::string>(2, [](int x){ return std::to_string(x); });

I would like to create a version where the parameters are deduced by the compiler, such that I can call it as auto y = Apply(...);

Upvotes: 0

Views: 52

Answers (1)

The basic cookbook solution for applying a functor:

  1. Use forwarding references.
  2. std::forward the living daylights out of everything.
  3. decltype(auto) for the return type

Which we can use to simmer your code sample into this:

template<typename F, typename A>
decltype(auto) Apply(F&& f, A&& a) {
  return std::forward<F>(f)(std::forward<A>(a));
}

For extra seasoning, we can also supply an exception specification:

template<typename F, typename A>
decltype(auto) Apply(F&& f, A&& a) 
  noexcept(noexcept(std::forward<F>(f)(std::forward<A>(a)))) {
  return std::forward<F>(f)(std::forward<A>(a));
}

Upvotes: 3

Related Questions