Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one write a C++ lambda with a name so it can be called from somewhere?

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?

like image 755
user9639921 Avatar asked Aug 09 '18 06:08

user9639921


2 Answers

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.

like image 55
Gassa Avatar answered Sep 30 '22 21:09

Gassa


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.

like image 34
aalimian Avatar answered Sep 30 '22 19:09

aalimian