Reputation: 20823
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
Reputation: 170044
The basic c++14 cookbook solution for applying a functor:
std::forward
the living daylights out of everything.decltype(auto)
for the return typeWhich 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