C ++ callback implementation and callback implementation
The callback is that A passes A function pointer to B and then calls B. After B executes its own function, B executes the function pointer of A at an appropriate time, in this way, the mutual inclusion and connection between A and B can be avoided. Callback is A common technology that breaks down circular dependencies in large projects.
Typedef void (CALLBACK * MyCallBack) (const char *); typedef void (* MyFuncB) (MyCallBack, const char *); // CALLBACK function void CALLBACK FuncC (const char * pszStr) {std: cout <"FunC is Running" <std: endl; if (! PszStr) {return;} std: cout <pszStr <std: endl;} // sets the callback and executes FuncBvoid FuncA (MyFuncB pFunB, MyCallBack pCallBAck, const char * pszStr) {std: cout <"FunA is Running" <std: endl; if (pCallBAck & pFunB) {pFunB (pCallBAck, pszStr) ;}} void FunB (MyCallBack pCallBAck, const char * pszStr) {std: cout <"FunB is Running" <std: endl; if (pCallBAck) {pCallBAck (pszStr) ;}} void FuncD (void) {std: cout <"FunD is Running" <std: endl;} class CTestA {public: void SetCallBack (MyCallBack pCallBack, const char * pszStr) {std: cout <"SetCallBack" <std: endl; if (pCallBack & pszStr) {m_pCallBack = pCallBack; m_pszStr = (char *) pszStr;} DoCallBack ();} void DoCallBack () {std: cout <"DoCallBack Running" <std: endl; if (m_pCallBack) {m_pCallBack (m_pszStr) ;}} private: MyCallBack m_pCallBack; char * m_pszStr ;}; class CTestB {public: void static CALLBACK FuncCallBack (const char * pszStr) // non-static is troublesome {if (pszStr) {std: cout <pszStr <std: endl ;}}; int _ tmain (int argc, _ TCHAR * argv []) {FuncA (FunB, FuncC, "hello"); FuncD (); CTestA a;. setCallBack (CTestB: FuncCallBack, "hello"); return 0 ;}
Boost: bind can also implement similar functions