- [&](int a){return a <x;}
- // 其中 x 为 lambda 表达式所在局部作用域的变量, 且以引用的方式被捕获.
- // [&]是一个捕获列表, 其指出 lambda 中使用的所有局部名字 (如 x) 将通过引用访问.
- // 若只希望捕获 x, 则可写成[&x]
- // 若希望给生成的函数对象传递一个 x 的拷贝, 则写成[=x]
- // 捕获所有以值访问的局部名字用[=]
- // 什么也不捕获是[]
- // 具体应用实例
- template<typename C, typename Oper>
- void for_all(C& c, Oper op)
- {
- for (auto& x: c)
- op(x);
- }
- vector<unique_ptr<Shape>> v;
- for_all(v, [](unique_ptr<Shape>& ps){ps->draw();}); // 对指针容器的元素指向的每个对象执行特定操作
- for_all(v, [](unique_ptr<Shape>& ps){ps->rotate(45);});
- // lambda 的泛型表示
- template<class S>
- void rotate_add_draw(vector<S>& v, int r)
- {
- for_all(v, [](auto& s){s->rotate(r); s->draw();});
- }
- vector<Shape*> v2;
- rotate_add_draw(v2, 90);
来源: http://www.bubuko.com/infodetail-3301424.html