今天看了一篇文章,收藏一下代码。读一读很有激情
#include <iostream> #include <string> #include <vector> using namespace std; template < class Class, typename ReturnType, typename Parameter > class SingularCallBack { public: typedef ReturnType (Class::*Method)(Parameter); SingularCallBack(Class* _class_instance, Method _method) { //取得对象实例地址,及调用方法地址 class_instance = _class_instance; method = _method; }; ReturnType operator()(Parameter parameter) { // 调用对象方法 return (class_instance->*method)(parameter); }; ReturnType execute(Parameter parameter) { // 调用对象方法 return operator()(parameter); }; private: Class* class_instance; Method method; }; 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++) { bool b=callback_list[i]("abc"); } for (unsigned int i = 0; i < callback_list.size(); i++) { callback_list[i].execute("abc"); } cin.get(); return true; }