c++11的lambda表示式與傳統的函式指標
阿新 • • 發佈:2019-01-10
#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;
}
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;
}