I need to accept lambda function as a parameter and figure out its return type. So far, I couldn't come up with anything workable. Here is the example:
template <typename T1, typename T2>
T1 foo(T2 arg, std::function<T1(T2)> f)
{
return f(arg);
}
...
int n = foo(3, [](int a){ return a + 2; }); <-- ERROR!
How can it be done? Boost solution is OK, too.
You shouldn't pass std::function as a parameter. It has some overhead because it uses type erasure to store any type of callable, such as function pointers, functors, lambdas (which are just an automatically generated functor), etc. Instead, you should just template the function type. Then you can use a trailing return type to figure out the return type of the function:
template <typename T, typename Function>
auto foo(T arg, Function f) -> decltype(f(arg))
{
return f(arg);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With