一段关于c++11中lambda表达式和std::function的体验代码

 1 #include <iostream>
 2 #include <string>
 3 #include <functional>
 4 
 5 // lambda表达式可以使用std::function封装
 6 std::function<std::string(void)> getLambda1() {
 7     return [](){return "She said: ";};
 8 }
 9 
10 // 要使用lambda表达式作为参数,需要使用函数模版
11 template<typename Lambda>
12 std::function<void(void)> getLambda2(Lambda l, const std::string& name) {
13     return [&](){
14         l(name);
15         std::cout << "Do you know me?" << std::endl;
16     };
17 }
18 
19 // 普通函数
20 void foo() {
21     std::cout << "I am foo!" << std::endl;
22 }
23 
24 // 成员函数
25 class CFoo {
26 public:
27     virtual void foo() {
28         std::cout << "I am CFoo::foo!" << std::endl;
29     }
30 };
31 
32 int main() {
33     // auto类型可以自动推演出lambda表达式的类型
34     auto lam1 = [&](const std::string& name) {
35         std::cout << (getLambda1())() << "I am " << name << ", a lambda expression!" << std::endl;    
36     };
37     
38     lam1("Lucy");
39     getLambda2(lam1, "Lily")();
40     
41     // 在不使用第三方库的情况下,函数指针和成员函数指针终于可以是一个东西了
42     {
43         std::function<void()> f = foo;
44         f();
45         CFoo bar;
46         f = std::bind(&CFoo::foo, &bar);
47         f();
48     }
49 }
50 
51 //gcc 4.6.2 编译通过

 

posted @ 2012-10-19 02:50  Y3G  阅读(2159)  评论(0编辑  收藏  举报