How to design universal callback mechanism
Many programs require a common callback mechanism that does not have to care about their class types. For example, in an event-driven system that calls the GUI component member function, the actual type information is not known before calling. At this point, you can create a generic callback template to process this task. The first parameter of this template is the class that its member function is called, and the second template parameter is a pointer, pointing to the member function of the class. The key tip of this is based on (or depends on) first parameters: Template Class Callback {/ ** /}; this template implementation Not complicated, there is a reference to T, it is a class, its member function is called, a constructor and a member function called Execute (), called the callback member function: Template Class Callback {public: Callback (T & T): Object (t) {} // Assign Actual Object to TVOid Execute () {(Object. * F) ();} // Launch Callback FunctionPrivate: T & object;}; Remember: In order to call the member function through the member pointer, the pointer to the actual object must be referenced. That's why this template has a T & as a data member, now suppose we want to use this callback template to perform a callback function of class A: Class A {public: void f ();}; here is an instantiation of the template: The template parameters must be a constant expression. Therefore, you cannot use variables as the address of this member function. And use the & operator to accept the address of the function. Finally, use the template object as a parameter. You want to call the object of its member function: int main () {a a; // first create a target callback c (a); // instantiation template C.EXECUTE (); // Call the callback member function} You can use this callback template for any class, as long as the member function name called is the same.