[] {
std::cout << "hello lambda" << std::endl;
} ();
auto l = [] {
std::cout << "Hi\n";
};
l();
auto l2 = [] (const std::string& s) {
std::cout << s << "\n";
};
l2("Hello");
auto l3 = [] {
return 42;
};
std::cout << l3() << "\n";
auto l4 = [] () -> double {
return 42;
};
std::cout << l4() << "\n";
Inside the lambda introducer (brackets at the beginning of a lambda), you can specify a capture to access data of outer scope that is not passed as an argument:
1. [=] 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.
2. [&] 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.
int x=0;
int y=42;
auto qq = [x, &y] {
std::cout << "x=" << x << "\n";
std::cout << "y=" << ++y << "\n";
};
qq();
std::cout << "final y=" << y << "\n";
[x, &y], you could also have specified [=, &y] to pass y by reference and all other objects by value.
auto q = [=, &y] {
std::cout << "x=" << x << "\n";
std::cout << "y=" << ++y << "\n";
};
q();
std::cout << "final y=" << y << "\n";
auto f = [x] () mutable {
std::cout << ++x << "\n";
std::cout << ++x << "\n";
};
f();
f();
std::cout << "x=" << x << "\n";
auto: returns by value:
auto returnLambda(){ // return by value
return [] (int x, int y) {
return x*y;
};
}
auto m = returnLambda();
std::cout << m(5,9) << "\n";
decltype(auto): returns the exact expression in the return statement (i.e., return a prvalue):
decltype(auto) returnLambda(){
return [] (int x, int y) {
return x*y;
};
}
decltype(auto) m = returnLambda();
std::cout << m(5,9) << "\n";
std::function<>:
std::function<int(int,int)> returnLambda(){
return [] (int x, int y) {
return x*y;
};
}
auto m = returnLambda();
std::cout << m(5,9) << "\n";