c++11的lambda表达式与传统的函数指针

时间:2021-12-13 18:41:17
#include <iostream>
using namespace std;
#include <functional> //std::function 头文件


//传统的函数指针
typedef int(*fun0)(int n);
int testfun(int n)
{
    return n;
}
//Lambda表达式
class CBase 
{


};
class CA : public CBase
{
public:
    CA(int n) : m_id(n) {}
    int getid() { return m_id; }
private:
    int m_id;
};
class CB : public CBase
{
public:
    CB(int n) : m_id(n) {}
    int getid() { return m_id; }
private:
    int m_id;
};


#define CL(__className__) [](int n){ return new __className__(n); }


int main()
{
    //函数指针
    fun0 pfun0 = testfun;
    cout << pfun0(888) << endl;
    
    //lambda表达式
    std::function<CBase*(int)> funA = CL(CA);
    CBase* pA = funA(1);
    cout << ((CA*)pA)->getid() << endl;


    std::function<CBase*(int)> funB = CL(CB);
    CBase* pB = funB(2);
    cout << ((CB*)pB)->getid() << endl;


    system("pause");
    return 0;
}