C++风格的回调对象方法. 采用template实现

时间:2022-10-27 08:54:56

今天看了一篇文章,收藏一下代码。读一读很有激情

#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();
AClass a2();
AClass a3(); 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 = ; i < callback_list.size(); i++)
{
bool b=callback_list[i]("abc");
} for (unsigned int i = ; i < callback_list.size(); i++)
{
callback_list[i].execute("abc");
}
cin.get();
return true; }