首页 > 代码库 > 2016-12-14:通过static关键字,使用类成员函数作为回调函数

2016-12-14:通过static关键字,使用类成员函数作为回调函数

#include <iostream>

using namespace std;

class Callee
{
public:
    void PrintInfo(int i)
    { cout << "printf info " << i << endl; }
    
    static void OnCallback(Callee* callee, int i)
    {
        callee->PrintInfo(i);
    }
};

typedef void(*CallbackFunctor)(Callee*, int);

class Caller
{
public:
    void SetCallback(CallbackFunctor func, Callee *callee)
    {
        m_callBack = func;
        m_callee = callee;
    }
    
    void DoCallback(int i)
    {
        m_callBack(m_callee, i);
    }
private:
    CallbackFunctor m_callBack;
    Callee *m_callee;
};

int main()
{
    Caller caller;
    Callee callee;
    caller.SetCallback(Callee::OnCallback, &callee);
    caller.DoCallback(10);

    Caller caller2;
    Callee callee2;
    caller2.SetCallback(Callee::OnCallback, &callee2);
    caller2.DoCallback(20);
}

2016-12-14:通过static关键字,使用类成员函数作为回调函数