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


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

    #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;
    
    }
  • 相关阅读:
    ACM——Points on Cycle
    ACM——A Simple Problem with Integers(线段树的精华版)
    HDU2524——矩形A+B
    ACM——Hero(类似贪心算法)
    用N个三角形最多可以把平面分成几个区域——acm
    ACM——敌兵布阵(经典的线段树)
    ACM——I Hate It(线段树的进化版)
    ACM——今年暑假不AC
    ACM题目Who's in the Middle
    内部排序算法
  • 原文地址:https://www.cnblogs.com/shit/p/3184497.html
Copyright © 2020-2023  润新知