C ++ callback implementation and callback implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.