简体   繁体   中英

I can't pass lambda with reference capture

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.

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); };

A lambda (with captures) is not the same as a function pointer, and cannot be converted to one.

A capture-less lambda can be converted to a function pointer.

See CPPReference , specifically the bit that begins:

A generic captureless lambda has a user-defined conversion function template with the same invented template parameter list as the function-call operator template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM