c++ 回调类成员函数实现
Posted 阳台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++ 回调类成员函数实现相关的知识,希望对你有一定的参考价值。
实现类成员函数的回调,并非静态函数;区分之
#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
以上是关于c++ 回调类成员函数实现的主要内容,如果未能解决你的问题,请参考以下文章