CallbackProxy.h
#ifndef __CALLBACK_PROXY_H__
#define __CALLBACK_PROXY_H__
//Tobject:调用对象的类型,Tparam回调函数参数的类型
template<typename Tobject, typename Tparam>
class CCallbackProxy
{
//指向Tobject类型对象的成员函数指针,参数类型为Tparam*
typedef void (Tobject::*CbFun)(Tparam*);
public:
//设置回调函数
void Set(Tobject *pInstance, CbFun pFun);
//调用回调函数
bool Exec(Tparam* pParam);
private:
CbFun pCbFun; //指向Tobject类型对象的成员函数指针
Tobject* m_pInstance; //指向Tobject类型对象指针
};
//注意: 下面格式的写法!!!
//设置调用对象及其回调函数
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 <stdio.h>
#include <iostream>
#include "CallbackProxy.h"
using namespace std;
//对象声明
class CTest
{
public:
CTest(int nNum);
void CbPrintSum(int *pnAddNum){printf("The Sum is %d\n", m_nSum+*pnAddNum);};
private:
int m_nSum;
};
CTest::CTest(int nNum):
m_nSum(nNum)
{
}
int main(int argc, char* argv[])
{
//定义回调对象
CCallbackProxy<CTest, int> CbProxy;
//定义test对象
CTest TestInstance(100);
//将test对象以及该对象的函数注册给回调对象
CbProxy.Set(&TestInstance, &CTest::CbPrintSum);
//执行回调对象的函数即调用test对象的函数CbPrintSum()
int nNum = 50;
CbProxy.Exec(&nNum);
return 0;
}