Lambdas
suggest changeSyntax
- [default-capture, capture-list] (argument-list) mutable noexcept-specifier attributes -> return-type { lambda-body } // Order of lambda specifiers and attributes.
- [capture-list] (argument-list) { lambda-body } // Common lambda definition.
- [=] (argument-list) { lambda-body } // Captures all needed local variables by value.
- [&] (argument-list) { lambda-body } // Captures all needed local variables by reference.
- [capture-list] { lambda-body } // Argument list and specifiers can be omitted.
Parameters
| Parameter | Details |
|---|---|
| default-capture | Specifies how all non-listed variables are captured. Can be = (capture by value) or & (capture by reference). If omitted, non-listed variables are inaccessible within the lambda-body. The default-capture must precede the capture-list. |
| capture-list | Specifies how local variables are made accessible within the lambda-body. Variables without a prefix are captured by value. Variables prefixed with & are captured by reference. Within a class method, this can be used to make all its members accessible by reference. Non-listed variables are inaccessible, unless the list is preceded by a default-capture. |
| argument-list | Specifies the arguments of the lambda function. |
mutable |
(optional) Normally variables captured by value are const. Specifying mutable makes them non-const. Changes to those variables are retained between calls. |
| noexcept-specifier | (optional) Specifies whether the lambda may throw; for example, noexcept. |
| attributes | (optional) Any attributes for the lambda function. For example, if the lambda-body always throws an exception then [[noreturn]] can be used. |
-> return-type |
(optional) Specifies the return type of the lambda function. Required when the return type cannot be determined by the compiler. |
| lambda-body | A code block containing the implementation of the lambda function. |
Remarks
C++17 introduces constexpr lambdas, which can be evaluated at compile time. A lambda is implicitly constexpr if it satisfies the constexpr requirements. The constexpr keyword says so explicitly:
// Explicitly define this lambda as constexpr
[]() constexpr {
//Do stuff
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents