I want to capture a 'reference' to a lambda, and I thought that a function pointer would do the trick, as in:
int (*factorial)(int) = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
but I get cannot convert from main::lambda<......> to int(_cdecl *)(int).
What's the proper way to point to a lambda then?
Since the lambda is not stateless, it cannot be converted to a function pointer. Use std::function instead.
std::function<int(int)> factorial = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
This would be closest to what you have already:
std::function<int (int)> factorial = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
normally you could also use auto, but in this case it doesn't work because the function is recursive.
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