c++11的lambda表達式與傳統的函數指針

#include
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章