Is it possible to pass a lambda function as a function of some type?
For example, I have
typedef double(*Function)(int, double);
How can I convert a lambda function to the type?
For a stateless lambda, this conversion is available implicitly:
Function f = [](int, double) -> double {};
If you just want to convert the lambda expression itself, you can use the unary +
operator to achieve this:
auto* p = +[](int, double) -> double {}; // p is of type double(*)(int, double)
A lambda with a capture offers no such conversion, since it is not semantically equivalent to a (stateless) function (this applies even to the case of a default capture that doesn't end up capturing anything).
You could use std::function
instead of a plain function pointer. This would allow to hold lambdas even when they have captures:
#include <iostream>
#include <functional>
typedef std::function<double(int, double)> Function;
int main()
{
Function f;
int i = 4;
f = [=](int l, double d){ return i*l*d; };
std::cout << f(2, 3);
}
[Live Demo]
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