identifier(&/=) 或 this 在 capture 子句中出现的次数不能超过一次。示例:
1 2 3 4 5 6 7 8
structS {voidf(int i); };
void S::f(int i) { [&, i]{}; // OK [&, &i]{}; // ERROR: i preceded by & when & is the default [=, this]{}; // ERROR: this when = is the default [i, i]{}; // ERROR: i repeated }
Lambda可变参数模板
1 2 3 4 5
template<class... Args> voidf(Args... args) { auto x = [args...] { return g(args...); }; x(); }
参数列表
1 2 3 4
int y = [] (int first, int second) { return first + second; };
1 2 3 4 5
// C++14,创建模板 auto y = [] (auto first, auto second) { return first + second; };
在 C++14 中,如果参数类型是泛型,则可以使用 auto 关键字作为类型说明符。 这将告知编译器将函数调用运算符创建为模板。 参数列表中的每个 auto 实例等效于一个不同的类型参数。
template <typename C> voidprint(conststring& s, const C& c){ cout << s; for (constauto& e : c) { cout << e << " "; } cout << endl; }
intmain() { constint elementCount = 9; vector<int> v(elementCount, 1); int x = 1, y = 1; //斐波那契:每个等于前两个的和 generate_n(v.begin() + 2, elementCount - 2, [=]() mutablethrow() -> int { int n = x + y; x = y; y = n; return n; }); print("vector v after call to generate_n() with lambda: ", v); cout << "x: " << x << " y: " << y << endl; // x y 仍为1 fillVector(v); print("vector v after 1st call to fillVector(): ", v); fillVector(v); print("vector v after 2nd call to fillVector(): ", v); }
输出:
1 2 3 4
vector v after call to generate_n() with lambda: 1 1 2 3 5 8 13 21 34 x: 1 y: 1 vector v after 1st call to fillVector(): 1 2 3 4 5 6 7 8 9 vector v after 2nd call to fillVector(): 10 11 12 13 14 15 16 17 18