Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting lambda as function parameter and extracting return type [duplicate]

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.

like image 512
Alex Blekhman Avatar asked Apr 30 '26 22:04

Alex Blekhman


1 Answers

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);
}
like image 103
Rapptz Avatar answered May 03 '26 13:05

Rapptz