[英]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.