I found a post on how to create a recursive lambda, but it is not clear how to return it from a function.
As far as I see, in the code below, captured func
refers to a destroyed object:
#include <iostream>
#include <functional>
std::function<int (int)> make_lambda()
{
std::function<int (int)> func;
func = [&func](int val)
{
if (val < 10)
{
return func(val + 1);
}
return val;
};
return func;
}
int main()
{
std::cout << make_lambda()(0);
return 0;
}
How to make this code work?
Is there a better way than using std::shared_pointer<std::function<int (int)>>
?
void make_lambda(std::function<int (int)>&)
is not an option.
EDIT1:
Why is there no this
allowing lambdas to refer to themselves?