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

A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:

std::string key;
std::map<std::string, int> v;

one can write the following:

std::find_if( v.begin(), v.end(), [&](auto const& elem){ return elem.first == key; } );

but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:

auto matches_key = [&](auto const& elem){ return elem.first == key; };

std::find_if( v.begin(), v.end(), matches_key );

it is clearer that we do want the equality comparison and the readability is improved.


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.