In order to write a recursive lambda function, you must perform the following:
- Define the lambda in a function scope.
- Assign the lambda to an std::function wrapper.
- Capture the std::function object by reference in the lambda in order to call it recursively.
The following are examples of recursive lambdas:
- A recursive Fibonacci lambda expression in the scope of a function that is invoked from the scope where it is defined:
void sample()
{
std::function<int(int const)> lfib =
[&lfib](int const n)
{
return n <= 2 ? 1 : lfib(n - 1) + lfib(n - 2);
};
auto f10 = lfib(10);
}
- A recursive Fibonacci lambda expression returned by a function, that can be invoked from any scope:
std::function<int(int const)> fib_create()
{
std::function<int(int const)> f = [](int const n)
{
std::function<int(int const)> lfib = [&lfib](int n)
{
return n <= 2 ? 1 : lfib(n - 1) + lfib(n - 2);
};
return lfib(n);
};
return f;
}
void sample()
{
auto lfib = fib_create();
auto f10 = lfib(10);
}