Lambda Expressions
Lambda Expressions
are closure
, encapsulating a small number of statements, passed to a function
.
Structure
[] () mutable throw () -> int {
// body
}
[]
iscapture clause
orlambda introducer
, it is used to determine if the expression accesses outsidevariables
byvalue
or byreference
.()
isparameter list
orlambda declarator
.
Optional and mandatory parts
Only capture clause
and body
are mandatory, rest are optional.
Capture Clause
A capture clause
introduces new variables inside the body from the outside scope
.
Empty
Specifies that the body accesses no variables
from outside scope
.
[] {
}
Value
Specifies that the variables
being accessed are accessed by value
.
[x] {
// x is accessed by value
int local_var_to_lambda = x;
}
Reference
Specifies that the variables
being accessed are accessed by reference
.
[&x] {
// x is accessed by reference
x = 420;
}
Default
We can specify a default behavior for identifiers inside the capture clause
.
[=] {
// all variables are accessed by value
}
[&] {
// all variables are accessed by reference
}
We can specify the exceptions for certain variables as well
[&, x] {
// Access all variables by reference
// but x by value
}
[=, &x] {
// Access all variables by value
// but x by reference
}
Parameter List
Similar to parameter list for functions
.
Mutable Specification
Enables to modify variables
that were captured by value
.
Exception Specification
We can optionally specify noexcept
if the expressions throws no exception
.
[] noexcept {
}
Return Type
Body
Similar to function
body.
Example
#include <iostream>
void foo (float a) {
std::cout << "Foo: " << a << std::endl;
}
int main () {
int x = 65;
int y = 2;
foo( // (1)!
[&, y] // (2)!
(float i) // (3)!
-> int { // (4)!
x++; // (5)!
float value = x + y + i + 1; // (6)!
return value;
}
(0.4) // (7)!
);
std::cout << "x: " << x << std::endl; // (8)!
std::cout << "y: " << y << std::endl; // (9)!
}
- Calls
foo()
. - Captures all
variables
by reference except fory
. - Takes a
float
parameter. - Converts the
return value
toint
. - Increments
x
which was accessed by reference. - Compute a
float
value. - Invokes the expression with
0.4
as input. - Prints
x
to check value. - Prints
y
to check value.