Lambda
minimum form of lambda in C++11 is like this:
#include
using namespace std;
int main() {
[](){};
return 0;
}
and it compiles. It is just a definition of minimum lambda function.
Minimum lambda function call is like this:
[](){}();
explanation of every element is below.
first "[]" is called lambda introducer. I will write usage at the end of this entry.
second () is function arguments.
third {} is function body.
last () is lambda function call.
I will introduce simple examples below.
1. hello world in lambda is like this:
[]{std::cout << "hello lambda" << std::endl;}();
it will output string "hello lambda".
2. lambda function can be assigned to variable;
auto func = []{cout << "assign to func" << endl;};
func();
3. lambda function can be passed to another function as argument.
template
void f(Func func) {
func();
}
f([]{cout << "pass to function as argument" << endl;});
4. passing argument to lambda function
[](string const& str){cout << str << endl;}("hah");
5. declare return type of lambda function implicitly.
auto b = []()->float { return 3.14;}();
float is return type.
6. if we want to access local names we use lambda introducer [].
string x = "I am local string which is outside of lambda function scope";
[&](string const& str){ x += str;}(". reference capture can change value of local variable");
output will be "I am local string which is outside of lambda function scope. . reference capture can change value of local variable"
copy capture is [=].
we can specify which variable is captured by reference or copy.
int x,y,z,n;
[&, x, y]{}; //only a and b is copy capture. the others are captured by reference.
[=, &x]{}; // only x is captured by reference. the others are captured by copy.
And there was tons of features.
No comments:
Post a Comment