I'm trying to return a lambda function which captures a variable from its current scope. When I don't capture a variable, the lambda function is returned and can be executed with no problem:
#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;
}
If vl
attempts to capture a variable, the compiler won't compile it anymore:
#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 0;
}
I have already tried casting the second lambda to VoidLambda, but the problem remains the same.
I'd like to know what the difference between the first and second lambda expression is, and how to solve the problem (i.e. return the lambda function with captures).