Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?
One use of this is to have a function access the enclosing scope.
In C++, we don't have nested functions as we do in some other languages. Having a named lambda solves this problem. An example:
#include <iostream>
int main ()
{
int x;
auto fun = [&] (int y) {
return x + y;
};
std::cin >> x;
int t;
std::cin >> t;
std::cout << fun (fun (t));
return 0;
}
Here, the function fun
is basically a nested function in main
, able to access its local variables.
We can format it so that it resembles a regular function, and use it more than once.
When your lambda is a recursive function by itself you have no choice but to give it a name. Also, an auto
keyword won't suffice and you would HAVE to declare it using an std::function
with the return type and the argument list.
Below is the example for a function that returns the Nth Fibonacci number:
std::function<int(int)> fibonacci = [&](int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
You have to give it a name in order to capture it with &
. And auto
won't work since lambda needs its to know its types before calling itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With