通过C++11的bind和function实现类的成员函数作为回调函数
下面是一简单例子:
#include "stdafx.h"
#include <functional>
using namespace std;
using namespace std::placeholders;
typedef function<bool()> OnPrintf;
class A
{
public:
A();
~A();
bool printfMsg();
};
A::A()
{
}
A::~A()
{
}
bool A::printfMsg()
{
printf("这里是A类的回调函数\n");
return true;
}
class B
{
public:
B();
~B();
void setCallBackFunc(OnPrintf pFunc);
void run();
private:
OnPrintf pPrintf;
};
B::B()
{
}
B::~B()
{
}
void B::setCallBackFunc(OnPrintf pFunc)
{
pPrintf = pFunc;
}
void B::run()
{
printf("这里是B类中函数.\n");
pPrintf();
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
B b;
OnPrintf pFunc = bind(&A::printfMsg, &a);
b.setCallBackFunc(pFunc);
b.run();
return 0;
}
运行结果: