[转][c++0x/c++11] lambda 表达式

38 篇文章 5 订阅

原文地址:http://blog.csdn.net/saga1979/article/details/7212639


lambda是c++0x提供的重大新特性。通过lambda表达式能很方便的创建简单的函数对象(你也可以创建复杂的函数对象,没人能阻止你),这在很多需要提供回调函数的场合非常有用。vc10及以上(gcc4.5及以上)版本的编译器都实现了lambda表达式。(本文中给出的代码示范使用的编译器为vc10+sp1或者gcc 4.6.1,有区别会特别指出)。

1、hello,lambda

在C++0x中,lambda表达式隐式定义和构造无名函数对象(行为类似手写的函数对象):

 

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4.   
  5. using namespace std;  
  6.   
  7. template<typename T>  
  8. class print  
  9. {  
  10. public:  
  11.     void operator()(T n)  
  12.     {  
  13.         cout<<n <<" ";  
  14.     }  
  15. };  
  16.   
  17. int main()  
  18. {  
  19.     vector<int> vec;  
  20.     for(int i=0; i<10; i++)  
  21.         vec.push_back(i);  
  22.     cout<<"print from lambda:";  
  23.     for_each(vec.begin(), vec.end(), [](int n){cout<<n<<" ";});  
  24.     cout<<endl<<"print from function object:";  
  25.     print<int> p;  
  26.     for_each(vec.begin(), vec.end(), p);   
  27.     cout<<endl;  
  28.     return 0;  
  29. }  

 

程序运行结果:

print from lambda:0 1 2 3 4 5 6 7 8 9
print from function object:0 1 2 3 4 5 6 7 8 9

看得出来,使用lambda能简化代码。

[]是lambda的前导符号,告诉编译器一个lambda表达式要开始了。(int n)是lambda的参数声明,而{cout<<n<<" ";}是无名函数对象被调用操作的函数体。

问题:如何主动调用lambda?

就跟你调用函数对象一样:

[cpp]  view plain copy
  1. int num = [](int num)->int{return ++num;}(10);  
  2. cout<<num<<endl;  


 

问题:如何“保存”已定义的lambda?

这涉及到c++0x的另外一个关键字auto,这里对它就不细说了。

[cpp]  view plain copy
  1. auto lambda = [](int num)  
  2. {  
  3.     cout<<++num<<endl;  
  4. };  
  5. lambda(10);  

2、lambda的语法

前导                            声明(可选)                大括弧(函数体)

(lambda-introducer     lambda-delcarator        compound-statement)

下面分别对其进行简单的说明:

lambda前导(lambda-introducer):

[lambda-capture(可选)],捕获(capture)参数是可选的,默认([])就是啥都不捕获

[cpp]  view plain copy
  1. int num =10;  
  2. []  
  3. {  
  4.     cout<<num<<endl;//这里行不通  
  5. }();  


如果想在lambda表达式内访问外部的数据,可使用以下方式传递变量:

[cpp]  view plain copy
  1. [=]//值传递所有变量    
  2. 02.    [&]//引用所有变量    
  3. 03.    [var]//值传递变量    
  4. 04.    [&var]//引用传递变量    

 

[cpp]  view plain copy
  1. int num =10;  
  2. int another = 11;  
  3. [=]//所有传递的变量为const  
  4. {cout<<"num:"<<num<<" "<<"another:"<<another<<endl;}();  
  5.   
  6. [&]//引用所有变量  
  7. {  
  8.     num++;  
  9.     another++;  
  10. }();  
  11.   
  12. //num 和 another的值发生了改变  
  13. cout<<"num:"<<num<<" "<<"another:"<<another<<endl;  
  14.   
  15. [num]//只值传递num变量  
  16. {  
  17.     cout<<num<<endl;  
  18.     cout<<another<<endl; //错误,封闭函数体内的局部变量如果不在捕获列表中就不能被引用   
  19. }();  
  20. [&num]//只引用传递num变量  
  21. {  
  22.     num++;  
  23.     another++;//错误,封闭函数体内的局部变量如果不在捕获列表中就不能被引用   
  24. }();  


lambda声明(lambda-declarator):
  ( 参数列表 ) attribute-specifier(可选) mutable(可选)
  exception-specification(可选)  trailing-return-type(可选)

[cpp]  view plain copy
  1. int num =10;  
  2. [=]()mutable//当使用mutable关键字时,可以对值传递的变量进行“写”操作  
  3. {cout<<++num<<endl;}();  
  4.   
  5. cout<<num<<endl;//调用lambda后num 其实没变化  


下面的lambda返回值为bool,判断两个参数是否都小于某个变量的l,throw()表示没有异常抛出:

[cpp]  view plain copy
  1. bool f = [num](int a, int b) throw()->bool   
  2. {return num>a && num >b;}(9, 11);  


(mutalbe关键字和trailing-return-type都是c++0x标准增加的东西,这里只说lambda表达式)

需要注意的一点是,如果你指定了返回类型,那么必须在前导[]后面使用圆括弧,即使你没有参数声明。

[cpp]  view plain copy
  1. []()->boolreturn false;}//[]后面必须有()  

 

对于lambda的语法,画了个图,很形象,但还是建议大家参考一下:

http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2927.pdf

 

lambda前导中指定的捕获选项组合多变,但默认的捕获策略必须在前面,也就是说&、=只能在前面,特化的捕获在后面:

[cpp]  view plain copy
  1. int fst =1;  
  2. int sec = 2;  
  3. int third = 3;  
  4. [=,&fst]{};//除了fst,别的值传递  
  5. [&, fst]{};//除了fst,别的引用传递  
  6. [&fst,sec,third]{};//等同[=,fst]  
  7. [&fst,sec,&third]{};//等同[&,sec]  
  8. [fst,=]{};//非法  
  9. [fst,&]{};//非法   

 

lambda表达式可以嵌套,但嵌套在内的表达式不能捕获外层作用域内的局部变量(全局变量可以):

[cpp]  view plain copy
  1. struct test  
  2. {  
  3.     test(){num =0;}  
  4.     int num;  
  5.     void print()  
  6.     {  
  7.         cout<<num<<endl;  
  8.     }  
  9. };  
  10. test g_o;  
  11. int main()  
  12. {  
  13.     test local;   
  14.     [&local]  
  15.     {     
  16.         local.num = 100;          
  17.         [=](int num)->void  
  18.         {  
  19.             //local.num //错误,lambda体内不能引用外面作用域内的局部变量  
  20.             g_o.num = num;            
  21.         }(local.num);  
  22.     }();  
  23.     g_o.print();  
  24.     local.print();  
  25.     return 0;  
  26. }  

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值