• 成员函数對象


    template <typename ReturnType, typename ArgType>
    struct closure_entity_base
    {
        virtual ReturnType operator()(ArgType a)=0;
        virtual closure_entity_base* clone()const=0;
    };
    
    template <class ClassType, typename ReturnType, typename ArgType>
    struct closure_entity : closure_entity_base<ReturnType, ArgType>
    {
        ReturnType operator()(ArgType a)
        {
            return (m_object.*m_fp)(a);
        }
        closure_entity(ClassType& object, ReturnType (ClassType::*fp)(ArgType))
            :m_object(object), m_fp(fp)
        {}
        virtual closure_entity_base<ReturnType, ArgType>* clone()const
        {
            return new closure_entity(*this);
        }
        ClassType& m_object;
        ReturnType (ClassType::*m_fp)(ArgType);
    };
    
    template <typename ReturnType, typename ArgType>
    struct closure
    {
        template <class ClassType>
        closure(ClassType& object, ReturnType(ClassType::*fp)(ArgType))
            :entity(new closure_entity<ClassType, ReturnType, ArgType>(object, fp))
        {}
    
        ~closure(){delete entity;}
    
        closure(const closure& src)
        {
            entity = src.entity->clone();
        }
    
        closure& operator=(const closure& src)
        {
            if(&src!=this)
            {
                delete entity;
                entity = src.entity->clone();
            }
            return *this;
        }
    
        ReturnType operator()(ArgType a)
        {
            return (*entity)(a);
        }
    
        closure_entity_base<ReturnType, ArgType>* entity;
    };
    
    class Test
    {
    public:
        int foo(int x){return x*x;}
    };
    
    #include <iostream>
    
    int main( void )
    {
        Test t;
        closure<int, int> c(t, &Test::foo);
        std::cout << c(10) << '\n';
        return 0;
    }

  • 相关阅读:
    Android中的回调Callback
    vim编辑器配置及常用命令
    自定义View 和 ViewGroup
    BluetoothClass详解
    BluetoothServerSocket详解
    NSData转换成NSDictionary
    SDWebImage缓存图片的机制(转)
    非ARC和ARC下创建单利模式的宏定义,可以直接套用
    详细例子构建自定义cell
    使用FMDB框架来加载数据库
  • 原文地址:https://www.cnblogs.com/prajna/p/2934405.html
Copyright © 2020-2023  润新知