C++复习

C11 匿名函数(lambda表达式)

2018-05-24  本文已影响15人  凉拌姨妈好吃

1. 关于Lambda表达式

A lambda function is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a functor or function pointer). With lambda, creating quick functions has become much easier, and this means that not only can you start using lambda when you'd previously have needed to write a separate named function, but you can start writing more code that relies on the ability to create quick-and-easy functions.

由上面可以知道,如果要创建快速简便功能的,可以尽可能使用Lambda表达式,因为它相当于在你的源码中内联,可以提高效率。

2. 声明Lambda表达式

2.1 Lambda表达式的完整声明
[capture list] (params list) mutable exception-> return type { function body }

各项的具体含义

2.2 如何捕获外部变量

Lambda表达式的实现是通过创建一个"small class”,这个类重载了(),所以它的运行就像一个函数。
一个Lambda函数就是一个类的实例,当构造类时,周围环境中的任何变量都被传递到lambda函数类的构造函数中,并保存为成员变量。

2.2.1 有如下几种方式进行捕获

[] 不捕获任何变量
[&] 捕获任何变量,并作为引用在函数体使用
[=] 捕获任何变量,并拷贝一份在函数体使用
[=, &foo] 截取外部作用域中所有变量,并拷贝一份在函数体中使用,但是对foo变量使用引用
[this] 截取当前类中的this指针。如果已经使用了&或者=就默认添加此选项
[x, &y] x 按值捕获, y 按引用捕获.

2.2.2 如何使用捕获
string name;  
cin>> name;  
return global_address_book.findMatchingAddresses(   
    // notice that the lambda function uses the the variable 'name'  
    [&] (const string& addr) { return name.find( addr ) != string::npos; }   
);  

这里通过捕获可以使用外部变量name

3. 使用Lambda表达式

std::vector<int> some_list;
int total = 0;
for (int i=0;i<5;++i) some_list.push_back(i);
std::for_each(begin(some_list), end(some_list), [&total](int x) 
{
    total += x;
});
std::vector<int> some_list;
  int total = 0;
  int value = 5;
  std::for_each(begin(some_list), end(some_list), [&, value, this](int x) 
  {
    total += x * value * this->some_func();
  });

此例中total会存为引用, value则会存一份值拷贝. 对this的捕获比较特殊, 它只能按值捕获. this只有当包含它的最靠近它的函数不是静态成员函数时才能被捕获 如果this被捕获了,不管是显式还隐式的,那么它的类的作用域对Lambda函数就是可见的. 访问this的成员不必使用this->语法,可以直接访问.

上一篇下一篇

猜你喜欢

热点阅读