分类: C/C++
2013-02-27 17:24:02
The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.
In C++ a lambda function is defined like this
[]() { } // barebone lambda
or in all its glory
[]() mutable -> T { } // T is the return type, still lacking throw()
[] is the capture list, () the argument list and {} the function body.
The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:
You can mix any of the above in a comma separated list [x, &y].
The argument list is the same as in any other C++ function.
The code that will be executed when the lambda is actually called.
If a lambda has only one return statement, the return type can be omitted and has the implicit type ofdecltype(return_statement).
If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.
The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.