A callback that implements a class member function is not a static function;
#ifndef __callback_proxy_h_#define__callback_proxy_h_Template<typename TObject, TypeName tparam>classccallbackproxy{typedefvoid(TObject::* cbfun) (tparam*); Public: voidSet (TObject *pinstance, Cbfun pfun); BOOLExec (tparam*pparam); Private: Cbfun pcbfun; //callback function Pointertobject* m_pinstance;//Call Object}; Template<typename TObject, TypeName tparam>voidCcallbackproxy<tobject, Tparam>::set (tobject*pinstance, Cbfun pfun) {m_pinstance=pinstance; Pcbfun=Pfun; } Template<typename TObject, TypeName tparam>BOOLCcallbackproxy<tobject, Tparam>::exec (tparam*pparam) {(M_pinstance->*Pcbfun) (Pparam); return true; } #endif
Named as: CallbackProxy.h
1#include <iostream>2#include"CallbackProxy.h"3 4 classCTest5 {6 Public:7CTest (intnnum): M_nsum (nnum) {8 } 9 voidCbprintsum (int*pnaddnum) {TenStd::cout <<"The sum is:"<<m_nsum +*pnaddnum <<Std::endl; One } A Private: - intm_nsum; - }; the - - intMain () - { +Ccallbackproxy<ctest,int>Cbproxy; -CTest Test (Ten); +Cbproxy.set (&test, &ctest::cbprintsum); A at intnum = -; -Cbproxy.exec (&num); - return 0; -}
Named as: Test.cpp
g++ test.cpp-g-wall &&./a.out
C + + Callback class member function implementation