学C++11的同学,肯定都知道这样一个名词:lambda。lambda有一个最大的好处是:可以捕获一系列的变量来保证参数数量正确。那么,lambda到底是什么东西呢?为什么lambda的类型必须用auto推断呢?非C++11是不是也有可以像lambda一样捕获变量的类型呢?
其实,lambda其实是函数对象。如果你学C++用的书是《C++ Primer(第5版)》(白书,书皮上有水弄出来的数字11),那么在10.3.2节Biggies函数中,会看到两个调用lambda的函数:
stable_sort(words.begin(),words.end(),
[](const string &l,const string &r)
{return l.size()<r.size();});
以及:
auto wc=find_if(words.begin(),words.end(),
[sz](const string &s){return s.size()>=sz;});
其实,lambda在编译时被解析成函数对象。
比方说,stable_sort调用的lambda被解析为:
struct{bool operator()(const string &l,const string &r)
{return l.size()<r.size();}}()
而find_if调用的lambda为:
struct a{int sz;a(int i):sz(i){}
bool operator()(const string &s){return s.size()>sz;}}()
也就是说,lambda
[ catch_list ] ( parm_list )-> return_type {function_body;}
被编译成
struct struct_name{定义catch_list;
struct_name(与catch_list类型一一对应的类型 ct):catch_list初始化为ct{}
return_type operator()(parm_list){function_body;}
}
struct_name通常是不知道的,你无法准确指定,所以,lambda的类型只能用auto推断,而不能直接指定。