1. lambda
- lambda-introducer (捕获字段)
- lambda-parameter-declaration-list (变量列表)
- mutable-specification (捕获的变量可否修改)
- exception-specification (异常设定)
- lambda-return-type-clause (返回类型)
- compound-statement (函数体)
空:不能访问外部变量
=:按值访问外部变量,[var]按值访问var,[=]按值访问所有变量
&:引用方式访问外部变量,[&var]引用访问var变量,[&]引用访问所有变量
组合[=,&var]能够按照引用访问var和按值访问所有变量
特殊情况:lambda函数在某个成员函数里面时,[this]和[=]可以访问这个成员函数所能访问的对象
lambda表达式的作用是可以替换函数指针。
// declaring_lambda_expressions2.cpp // compile with: /EHsc /W4 #include <functional> #include <iostream> int main() { using namespace std; int i = 3; int j = 5; // The following lambda expression captures i by value and // j by reference. function<int (void)> f = [i, &j] { return i + j; };//声明定义f的时候,使用i的值传入,j的引用 // Change the values of i and j. i = 22; j = 44; // Call f and print its result. cout << f() << endl; //output:3+44=47 }直接调用生成运算结果:
- #include <iostream>
- int main()
- {
- using namespace std;
- int n = [] (int x, int y) { return x + y; }(5, 4);
- cout << n << endl;
- }
lambda的嵌套:
- #include <iostream>
- int main()
- {
- using namespace std;
- // The following lambda expression contains a nested lambda
- // expression.
- int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);
- // Print the result.
- cout << timestwoplusthree << endl;
- }
更高级嵌套的:
- #include <iostream>
- #include <functional>
- int main()
- {
- using namespace std;
- auto addtwointegers = [](int x) -> function<int(int)> {
- return [=](int y) { return x + y; };
- };
- auto higherorder = [](const function<int(int)>& f, int z) {
- return f(z) * 2;
- };
- auto answer = higherorder(addtwointegers(7), 8);
- cout << answer << endl;
- }
addtwointegers(7)生成了一个function<int(int)>函数,函数功能是计算7+输入的累加和
higherorder 可以看做是一个更高级的lambda,调用生成的addtwointegers(7),给它传入一个参数,计算结果
2. function包装器
function<>包装器可以将普通函数,lambad函数,函数对象统一分装起来,虽然它们不是相同的类型,但是经过了function模板后,它们可以转化为相同的function的对象
将函数作为参数,解决模板匹配效率低的问题。
int add(int i, int j) { return i + j; } //普通函数 // lambda表达式 auto mod = [](int i, int j){return i % j; }; // 函数对象类 struct divide { int operator() (int denominator, int divisor) { return denominator / divisor; } }; int main(int argc, char *argv[]) { map<char, function<int(int, int)>> binops = { { '+', add }, { '-', minus<int>() }, { '*', [](int i, int j){return i * j; } }, { '/', divide() }, { '%', mod }, };
//函数有两个参数, cout << binops['+'](10, 5) << endl; cout << binops['-'](10, 5) << endl; cout << binops['*'](10, 5) << endl; cout << binops['/'](10, 5) << endl; cout << binops['%'](10, 5) << endl; system("pause"); return 0; }