How to design a universal callback mechanism
ManyProgramA general callback mechanism is required. This callback mechanism does not need to care about their class types. For example, in an event-driven system that calls GUI component member functions, the actual type information is not known before the call. In this case, you can create a general callback template to streamline this task. The first parameter of the template is the class whose member functions are called. The second parameter of the template is a pointer pointing to the member functions of the class. The second parameter here is based on (or depends on) the first parameter:
Template <class T, void (T: * f) ()> class callback {/**/};
The implementation of this template is not complicated. There is a reference to T. It is a class, and its member functions will be called, a constructor and a member function called execute, it calls the callback member function:
Template <class T, void (T: * f) ()>
Class callback
{
Public:
Callback (T & T): Object (t) {}// assign actual object to T
Void execute () {(object. * f) ();} // launch callback function
PRIVATE:
T & object;
};
Remember: to call a member function using a member pointer, you must reference or use a pointer to an actual object. This is why the template has a T & as a data member. Now let's assume that we want to use this callback template to execute a callback function for Class:
Class
{
Public:
Void F ();
};
Here is the method for instantiating the template: The template parameter must be a constant expression. Therefore, you cannot use variables as the address of this member function. Use the & operator to accept the address of the function. Finally, use the template object as the parameter to pass the object whose member function you want to call:
Int main ()
{
A A; // create an object first
Callback <A, & A: F> C (a); // instantiate the Template
C.exe cute (); // call the callback member function
}
You can use this callback class template for any class type, as long as the name of the called member function is the same.