The callback function is a useful and important concept. When an event occurs, the system or other function will automatically invoke the function you defined. Callback functions are used in Windows programming, such as Hook callback functions: Mouseproc,getmsgproc and Enumwindows,drawstate callback functions, and many system-level callback procedures. Generally, we use the callback function is basically the C language style. This describes a C + + Style callback object method. Adopt template implementation.
Template < class class, TypeName ReturnType, TypeName Parameter > class Singularcallback {public:typedef Returntyp E (Class::* method) (Parameter); Singularcallback (class* _class_instance, method _method) {//Get object instance address, and call methods address class_instance = _class_instance; _method; }; ReturnType operator () (Parameter Parameter) {//Invoke object method return (Class_instance->*method) (Parameter); ReturnType Execute (Parameter Parameter) {//Invoke object method return operator () (Parameter); Private:class* class_instance; Method method; };
Example:
Here are two class implementations.
Class A {public:void output () {std::cout << "I am Class A:D" << Std::endl;}; Class B {Public:bool MethodB (a) {a.output (); return true;}};
Various invocation examples for Singularcallback:
A A; b b; singularcallback< b,bool,a >* CB; cb = new singularcallback< b,bool,a > (&B,&B::METHODB); if ((*CB) (a)) {std::cout << "CallBack fired successfully!" << Std::endl;} else {std::cout << "CallBack Fired unsuccessfully! "<< Std::endl; }
A A; b b; singularcallback< b,bool,a >* CB; cb = new singularcallback< b,bool,a > (&B,&B::METHODB); if (Cb->execute (a)) {std::cout << "CallBack fired successfully!" << Std::endl;} else {std::cout << "CallBack fired unsuccessfully!" << Std::endl; }
A A; b b; singularcallback< b,bool,a >CB (&B,&B::METHODB); if (CB (a)) {std::cout << "CallBack fired successfully!" << Std::endl;} else {std::cout << "CallBack Fi Red unsuccessfully! "<< Std::endl; }
Class AClass {public:aclass (unsigned int _id): ID (_id) {}; ~aclass () {}; bool Amethod (std::string str) {std::cout << ; "aclass[" << ID << "]:" << str << Std::endl; return true; }; private:unsigned int id; }; typedef Singularcallback < AClass, bool, std::string > Acallback; int main () {std::vector < acallback > callback_list; AClass A1 (1); AClass A2 (2); AClass A3 (3); Callback_list.push_back (Acallback (&A1, &aclass::amethod)); Callback_list.push_back (Acallback (&A2, &aclass::amethod)); Callback_list.push_back (Acallback (&A3, &aclass::amethod)); for (unsigned int i = 0, I < callback_list.size (); i++) {callback_list[i] ("abc");} for (unsigned int i = 0; i < CA Llback_list.size (); i++) {Callback_list[i].execute ("abc");} return true; }
Reference:
C + + Callback Solution