C++ 实现把非静态成员函数作为回调函数(非static)

C++ Thunk方式:

https://blog.twofei.com/616/

 

自定义代理类方式:

原文:http://qimo601.iteye.com/blog/1727645

CallbackProxy.h

#ifndef __CALLBACK_PROXY_H__
#define __CALLBACK_PROXY_H__  
  
//Tobject:调用对象的类型,Tparam回调函数参数的类型  
template<typename Tobject, typename Tparam>  
class CCallbackProxy  
{  
    typedef void (Tobject::*CbFun)(Tparam*);  
  
public:  
    void Set(Tobject *pInstance, CbFun pFun);  
    bool Exec(Tparam* pParam);  
  
private:      
    CbFun       pCbFun;     //回调函数指针  
    Tobject*    m_pInstance;    //调用对象  
};  
  
//设置调用对象及其回调函数  
template<typename Tobject, typename Tparam>  
void CCallbackProxy<Tobject, Tparam>::Set(Tobject *pInstance , CbFun pFun)  
{  
    m_pInstance = pInstance;   
    pCbFun = pFun;  
};  
  
//调用回调函数  
template<typename Tobject, typename Tparam>  
bool CCallbackProxy<Tobject, Tparam>::Exec(Tparam* pParam)  
{  
    (m_pInstance->*pCbFun)(pParam);  
    return true;  
}  
  
#endif  

 

test.cpp

#include "CallbackProxy.h"  
  
class CTest  
{  
public:  
    CTest(int nNum);  
    void CbPrintSum(int *pnAddNum){printf("The Sum is %d\n", m_nSum+*pnAddNum);};  
  
private:  
    int m_nSum;  
};  
  
int main(int argc,  char* argv[])  
{  
    CCallbackProxy<CTest, int> CbProxy;  
  
    CTest TestInstance(20);  
  
    CbProxy.Set(&TestInstance, &CTest::CbPrintSum);  
  
    int nNum = 1000;  
    CbProxy.Exec(&nNum);  
  
    return 0;  
}  
  
CTest::CTest(int nNum):  
m_nSum(nNum)  
{  
  
}  

 

 

你可能感兴趣的:(C++ 实现把非静态成员函数作为回调函数(非static))