实现类成员函数的回调,并非静态函数;区分之
#ifndef __CALLBACK_PROXY_H_
#define __CALLBACK_PROXY_H_ 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
命名为:CallbackProxy.h
#include <iostream>
#include "CallbackProxy.h" class CTest
{
public:
CTest(int nNum):m_nSum(nNum){
}
void CbPrintSum(int *pnAddNum){
std::cout << "The sum is: " <<m_nSum +*pnAddNum << std::endl;
}
private:
int m_nSum;
}; int main()
{
CCallbackProxy<CTest, int> CbProxy;
CTest test();
CbProxy.Set(&test, &CTest::CbPrintSum); int num = ;
CbProxy.Exec(&num);
return ;
}
命名为:test.cpp
g++ test.cpp -g -Wall && ./a.out