我无法通过引用捕获传递 lambda
I can't pass lambda with reference capture
以下代码因此错误而失败
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; };
我该如何解决这个问题?我需要 Capture 子句。
您只能使用无捕获 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.
因为 lambdas are not just ordinary functions 并捕获它需要 保存状态 ,
您找不到任何简单或常规的解决方案来使它们分配给函数指针。
要修复,您可以使用 std::function
,它将通过类型擦除来完成:
#include <functional> // std::function
int test;
std::function<float(int)> f = [&](int i) -> float {return static_cast<float>(test); };
lambda(带捕获)与函数指针不同,不能转换为函数指针。
无捕获 lambda 可以 转换为函数指针。
参见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.
以下代码因此错误而失败
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; };
我该如何解决这个问题?我需要 Capture 子句。
您只能使用无捕获 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.
因为 lambdas are not just ordinary functions 并捕获它需要 保存状态 , 您找不到任何简单或常规的解决方案来使它们分配给函数指针。
要修复,您可以使用 std::function
,它将通过类型擦除来完成:
#include <functional> // std::function
int test;
std::function<float(int)> f = [&](int i) -> float {return static_cast<float>(test); };
lambda(带捕获)与函数指针不同,不能转换为函数指针。
无捕获 lambda 可以 转换为函数指针。
参见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.