Following code fails with this error
E0413 no suitable conversion function from "lambda []float (int i)->float" to "float (*)(int i)" exists
int test;
float (*f)(int i) = [&](int i) -> float {return test; };
How do I fix this? I need the Capture clause.
The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.
C++ Lambdas Conversion to function pointer This feature is mainly useful for using lambdas with APIs that deal in function pointers, rather than C++ function objects. Conversion to a function pointer is also possible for generic lambdas with an empty capture list.
The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.
You can only do the above with capture-less lambdas.
See [expr.prim.lambda.closure] (sec 7)
The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator.
Since lambdas are not just ordinary functions and capturing it need to preserve a state, you can not find any simple or conventional solution to make them assign to function pointers.
To fix, you can use std::function
which will do it by type erasure:
#include <functional> // std::function
int test;
std::function<float(int)> f = [&](int i) -> float {return static_cast<float>(test); };
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