C++ Lambda Expressions

lambda functions

In C++, the regular function syntax is extended with the concept of a “callable”, I mean callable entiy or something that can be called in the same way as a function like static and pointing functions or functors.

Functors are objects with operator (), as we can see below:

struct S {
    void operator()(int i);
};
S s;
s(1);

Callables are used normally for the local context. For example for the custom comparison function.

For example:

void somefunction() {
    std::vector<int> v;
    ...
    strunct comparator {
        bool operator()(int a, int b) const {return a<b;}
    }
    std::sort(v.begin(), v.end(), comparator());
}

This is compact and local, but too verbose. We do not actually need to give this class a name, and we only ever want one instance of this class. In C++11, we have a much better approach, Lambda Expression:

void somefunction() {
    std::vector<int> v;
    ...
    auto comparator = [](int a, int b) const {return a<b;}
    std::sort(v.begin(), v.end(), comparator);
}

Lambda expressions finally came to C++ in the C++11 standard. Lambda expressions, also known as closures, lambda functions, function literals, or just lambdas, have their own unique syntax.

Note that in the example above the lambda expression didn’t define the return type. This is optional if you prefer is possible to do that:

void somefunction() {
    ...
    auto comparator = [](int a, int b) -> int const {return a<b;}
}