Lambdas (anonymous function objects) are a cornerstone of Functional Programming in C++. A lambda consists of a capture list, parameters, an optional return type, and a body.
The Capture List [ ]
[]- Captures nothing.[=]- Captures all local variables by value.[&]- Captures all local variables by reference.[this]- Captures the current object by pointer.[*this](C++17) - Captures the current object by value (safe for async).
Mutable Lambdas
By default, the operator() of a lambda is const (you cannot modify variables captured by value). Use mutable to allow modification.
int x = 10;
auto f = [x]() mutable { x++; return x; }; // OK
Generic Lambdas (C++14) and Templex Lambdas (C++20)
C++20 allows explicit template parameters in lambdas: []<typename T>(std::vector<T> const& v) { ... }.