1 [捕捉列表] (参数) mutable -> 返回值类型 {函数体}
1 []{}
1 int main(int argc, char* argv[]) 2 { 3 int a = 5, b = 7; 4 auto total = [](int x, int y)->int {return x + y; }; //接受两个参数 5 cout << total(a, b)<<endl; //12 6 auto fun1 = [=] {return a + b; }; //值传递捕捉父作用域变量 7 cout << fun1() << endl; //12 8 auto fun2 = [&](int c) {b = a + c; a = 1; }; //省略了返回值类型,引用捕获所有 9 fun2(3); //1 8 10 cout << a <<" "<< b << endl; 11 a = 5; b = 7; //被修改后,重新赋值 12 auto fun3 = [=, &b](int c) mutable {b = a + c; a = 1; }; //以值传递捕捉的变量,在函数体里如果要修改,要加mutaple,因为默认const修饰 13 fun3(3); 14 cout << a << " " <<b<< endl; //5,8 15 a = 5; b = 7; //被修改后,重新赋值 16 auto fun4 = [=](int x, int y) mutable->int {a += x; b += y; return a + b; }; 17 int t = fun4(10, 20); 18 cout << t << endl; //42 19 cout << a <<" "<< b << endl; //5 7 20 return 0; 21 }
块作用域以外的Lambda函数捕捉列表必须为空,因此这样的函数除了语法上的不同,和普通函数区别不大。
1 class Price 2 { 3 private: 4 float _rate; 5 public: 6 Price(float rate):_rate(rate){} 7 float operator()(float price) 8 { 9 return price*(1 - _rate / 100); 10 } 11 }; 12 13 int main(int argc, char* argv[]) 14 { 15 float rate=5.5f; 16 17 Price c1(rate); 18 auto c2 = [rate](float price)->float {return price*(1 - rate / 100); }; 19 20 float p1 = c1(3699); //仿函数 21 float p2 = c2(3699); //Lambda函数 22 23 return 0; 24 }
1 int main(int argc, char* argv[]) 2 { 3 int j = 12; 4 auto by_val = [=] {return j + 1; }; 5 auto by_ref = [&] {return j + 1; }; 6 cout << by_val() << endl; //13 7 cout << by_ref() << endl; //13 8 j++; 9 cout << by_val() << endl; //13 10 cout << by_ref() << endl; //14 11 return 0; 12 }
1 class const_val_lambda 2 { 3 public: 4 const_val_lambda(int v):val(v){} 5 public: 6 void operator()()const { val = 3; } //报错 7 private: 8 int val; 9 };
1 int main(int argc, char* argv[]) 2 { 3 int a = 3, b = 4; 4 5 auto total = [](int x, int y)->int {return x + y; }; 6 typedef int(*all)(int x, int y); 7 typedef int(*one)(int x); 8 9 all p; 10 p = total; 11 one q; 12 q = total; //报错,参数不一致 13 14 decltype(total) all_1 = total; 15 decltype(total) all_2 = p; //报错,指针无法转换为Lambda 16 17 return 0; 18 }
原文:https://www.cnblogs.com/WindSun/p/11182276.html