我正在尝试返回一个 lambda 函数,该函数从其当前作用域中捕获一个变量。当我不捕获变量时,将返回 lambda 函数并且可以毫无问题地执行:
#include <iostream>
typedef void(*VoidLambda)();
VoidLambda get() {
VoidLambda vl = []() {
std::cout << "hello" << std::endl;
};
return vl;
};
int main()
{
get()(); //prints "hello" as expected
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果vl试图捕获一个变量,编译器将不再编译它:
#include <iostream>
typedef void(*VoidLambda)();
VoidLambda get(const char* x) {
VoidLambda vl = [x]() { //Error: no suitable conversion function from "lambda []void ()->void" to "VoidLambda" exists
std::cout << x << std::endl;
};
return vl;
};
int main()
{
get("hello")();
return …Run Code Online (Sandbox Code Playgroud)