Lambdas 语法
no parameters: […] {…}
[] { std::cout << "hello lambda" << std::endl; }
You can call it directly:
[] { std::cout << "hello lambda" << std::endl; } (); // prints ‘‘hello lambda’’
or pass it to objects to get called:
auto l = [] { std::cout << "hello lambda" << std::endl; }; ... l(); // prints ‘‘hello lambda’’
has parameters: […] (…) {…}
A lambda can have parameters specified in parentheses, just like any other function:
auto l = [] (const std::string& s) { std::cout << s << std::endl; }; l("hello lambda"); // prints ‘‘hello lambda’’
It cannot be templates.
return something. Without any specific definition of the return type, it is
deduced from the return value. For example, the return type of the following lambda is int:[] { return 42; }
Others, the following lambda returns 42.0:
[] () -> double { return 42; }
Captures (Access to Outer Scope)
[=] means that the outer scope is passed to the lambda by value. Thus, you can read but not
modify all data that was readable where the lambda was defined.[&] means that the outer scope is passed to the lambda by reference. Thus, you have write access
to all data that was valid when the lambda was defined, provided that you had write access there.For example:int x=0; int y=42; auto qqq = [x, &y] { std::cout << "x: " << x << std::endl; std::cout << "y: " << y << std::endl; ++y; // OK // ++i; // ERROR!!!!! }; x = y = 77; qqq(); qqq(); std::cout << "finaly: " << y << std::endl;
OUTPUT:
x: 0 y: 77 x: 0 y: 78 finaly: 79
Instead of [x, &y], you could also have specified [=, &y] to pass y by reference and all other
objects by value.multable
To have a mixture of passing by value and passing by reference, you can declare the lambda as mutable. In that case, objects are passed by value, but inside the function object defined by the lambda, you have write access to the passed value. For example:
int id = 0; auto f = [id] () mutable { std::cout << "id: " << id << std::endl; ++id; // OK }; id = 42; f(); f(); f(); std::cout << id << std::endl;
has the following output:
id: 0 id: 1 id: 2 42
Type of Lambdas
Using Lambdas
本文来源:《C++ Standard Library》(2nd Edition) Typed By:IFuMI