So I've been learning about templates and lambdas so I tried to combine the two. I am trying to create a templated typedef that specifies what the lambda is supposed to return and accept. It works well for non capturing lambdas but it cannot handle any lambdas that capture. This is my code for now:
template<typename T>
using L = T(*)(T);
template<typename T>
T applyLambda(T var, L<T> lambda){
return lambda(var);
}
int main() {
const int a = 45;
int b = applyLambda<int>(3, [] (int x)->int { // non capturing lambda
return x+5;
});
std::cout << b << std::endl;
}
But if I change the function call to this:
int b = applyLambda<int>(3, [=] (int x)->int {
return x+a;
});
I get the following error:
candidate function template not viable: no known conversion from
'(lambda at main.cpp:15:31)' to 'L<int>' (aka 'int (*)(int)') for 2nd argument
T applyLambda(T var, L<T> lambda)
Now my question is what do I need to change here:
template<typename T>
using L = T(*)(T);
In order to accept lambdas that capture.
I do realize I could always do it like this but that would not specify lambda return type and parameters
template<typename T, typename LF>
T applyLambda(T var, LF lambda){