繁体   English   中英

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

[英]I can't pass lambda with reference capture

以下代码因此错误而失败

E0413 不存在从“lambda []float (int i)->float”到“float (*)(int i)”的合适转换 function

int test;   
float (*f)(int i) = [&](int i) -> float {return test; };

我该如何解决? 我需要捕获子句。

您只能使用无捕获 lambda 执行上述操作。

参见[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 .

由于lambda 不仅仅是普通函数,并且捕获它需要保留 state ,因此您找不到任何简单或常规的解决方案来将它们分配给 function 指针。


要修复,您可以使用std::function ,这将通过类型擦除来完成:

#include <functional> // std::function

int test;
std::function<float(int)> f = [&](int i) -> float {return static_cast<float>(test); };

lambda(带捕获)与 function 指针不同,不能转换为 1。

无捕获的 lambda可以转换为 function 指针。

请参阅CPPReference ,特别是开头的位:

通用无捕获 lambda 具有用户定义的转换 function 模板,该模板具有与函数调用运算符模板相同的发明模板参数列表。

暂无
暂无

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

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