实现类成员函数的回调,并非静态函数;区分之
#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
1 #include <iostream> 2 #include "CallbackProxy.h" 3 4 class CTest 5 { 6 public: 7 CTest(int nNum):m_nSum(nNum){ 8 } 9 void CbPrintSum(int *pnAddNum){ 10 std::cout << "The sum is: " <<m_nSum +*pnAddNum << std::endl; 11 } 12 private: 13 int m_nSum; 14 }; 15 16 17 int main() 18 { 19 CCallbackProxy<CTest, int> CbProxy; 20 CTest test(10); 21 CbProxy.Set(&test, &CTest::CbPrintSum); 22 23 int num = 100; 24 CbProxy.Exec(&num); 25 return 0; 26 }
命名为:test.cpp
g++ test.cpp -g -Wall && ./a.out
时间: 2024-10-12 07:52:31