简体   繁体   English

我无法通过参考捕获通过 lambda

[英]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 E0413 不存在从“lambda []float (int i)->float”到“float (*)(int i)”的合适转换 function

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.您只能使用无捕获 lambda 执行上述操作。

See [expr.prim.lambda.closure] (sec 7)参见[expr.prim.lambda.closure] (第 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. 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.由于lambda 不仅仅是普通函数,并且捕获它需要保留 state ,因此您找不到任何简单或常规的解决方案来将它们分配给 function 指针。


To fix, you can use std::function which will do it by type erasure:要修复,您可以使用std::function ,这将通过类型擦除来完成:

#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. lambda(带捕获)与 function 指针不同,不能转换为 1。

A capture-less lambda can be converted to a function pointer.无捕获的 lambda可以转换为 function 指针。

See CPPReference , specifically the bit that begins:请参阅CPPReference ,特别是开头的位:

A generic captureless lambda has a user-defined conversion function template with the same invented template parameter list as the function-call operator template.通用无捕获 lambda 具有用户定义的转换 function 模板,该模板具有与函数调用运算符模板相同的发明模板参数列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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