C++ Lambda表达式

Posted on 2020-06-24 16:53  金色的省略号  阅读(187)  评论(0编辑  收藏  举报

  C++ 11 标准的,Lambda表达式,基本语法如下:

[capture list] (parameter list) -> return type { function body }

  测试代码

#include <stdio.h>
int main()
{    
    int a = 4, b = 5;
    
    /* 注意,这是一个语句,分号结尾 */
    auto function = [](int x, int y) -> int { return x + y; };
              
    printf("%d\n", function(a,b));
    return 0;
}
View Code
#include <iostream>   
using namespace std;

class A{
public:
    void operator()(){
        cout << "void operator()()" << endl;
    }
};

template<typename T> 
void func(T t){  // t不是T类型的引用
    cout << "template<typename T> void func(T t)" << endl;
    t();  //!
}
 
void test(int arg ){    
    int x = 2;
    func<A > (A()  );         //对象//仿函数
    func<void(*)() > ([]() { cout << "[]() {  }" << endl;    }  );  //函数指针//lambda表达式
    /* 
    //void (*fun)()  =  []() { cout << "[]() {  }";    }; //lambda表达式加上分号才是语句!
    auto p1 = [=](int i )->double { cout << arg+x+i << endl; return 0.123;  }; //1+2+7
    cout << p1(7 ) << endl;
    auto p2 = []{cout << "p2" << endl;  };  //lambda表达式,必须永远包含捕获列表和函数体
    p2();     
     */
}

int main () 
{    
    test(1);
    return 0;
}
View Code