7 Expressions [expr]

7.5 Primary expressions [expr.prim]

7.5.5 Lambda expressions [expr.prim.lambda]

7.5.5.1 General [expr.prim.lambda.general]

lambda-expression:
lambda-introducer lambda-declarator compound-statement
lambda-introducer < template-parameter-list > requires-clause lambda-declarator compound-statement
lambda-introducer:
[ lambda-capture ]
lambda-declarator:
( parameter-declaration-clause ) decl-specifier-seq
   noexcept-specifier attribute-specifier-seq trailing-return-type requires-clause
A lambda-expression provides a concise way to create a simple function object.
[Example 1: #include <algorithm> #include <cmath> void abssort(float* x, unsigned N) { std::sort(x, x + N, [](float a, float b) { return std::abs(a) < std::abs(b); }); } — end example]
A lambda-expression is a prvalue whose result object is called the closure object.
[Note 1:
A closure object behaves like a function object.
— end note]
In the decl-specifier-seq of the lambda-declarator, each decl-specifier shall be one of mutable, constexpr, or consteval.
[Note 2:
The trailing requires-clause is described in [dcl.decl].
— end note]
If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were ().
The lambda return type is auto, which is replaced by the type specified by the trailing-return-type if provided and/or deduced from return statements as described in [dcl.spec.auto].
[Example 2: auto x1 = [](int i){ return i; }; // OK: return type is int auto x2 = []{ return { 1, 2 }; }; // error: deducing return type from braced-init-list int j; auto x3 = []()->auto&& { return j; }; // OK: return type is int& — end example]
A lambda is a generic lambda if the lambda-expression has any generic parameter type placeholders ([dcl.spec.auto]), or if the lambda has a template-parameter-list.
[Example 3: int i = [](int i, auto a) { return i; }(3, 4); // OK: a generic lambda int j = []<class T>(T t, int i) { return i; }(3, 4); // OK: a generic lambda — end example]