您的位置:首页 > 编程语言 > C语言/C++

关于Policy Based Class Design--《Modern C++ Design》读后感一

2006-12-26 19:11 459 查看
前不久阅读了一下 Andrei Alexandrescu的大作《Modern C++ Design》,深受启发。现写一些读后感,一个是促进自己学习,二者是希望大家交流,抛砖引玉。

说到底Policy Based Class Design是基于Templete模版的Templete组件设计技术,就是用内Templete来作为Policy为外Templete提供可配置的服务。

例如:


template<class T,Template<class> class  Policy1,Template<class>class Policy2 >


class PolicyBasedClass:public Policy1<T>,public Policy2<T>




...{


}



当然Policy1也可以不依赖于模版T。同样Policy2也可以。这样也当然也可以。

 


template<class T,class  Policy1,class Policy2 >


class PolicyBasedClass:public Policy1,public Policy2




...{


}



当然第一个例子更加具有通用性。

这样你可以代入不同的Policy Class,来改变PolicyBasedClass的行为。

而所有的配置都是在编译阶段完成的,而不是RunTime,所以没有任何的性能损失。

有人说,我可以加个参数,对这个Class做重载,当然是可以的,而且可以获得运行时刻的灵活性,当然系统的开销相对也会大一些。

所以个人认为,PolicyBasedClass更加适合于做一些Framework的工作。例如设计一个基础的框架库,这个技术就很实用。所以Loki也是这样子的一个库。


namespace SHFTest




...{


    template <class T>


    struct OpNewCreator




    ...{


        static T* Create()




        ...{


            return new T;


        }


    protected:




        ~OpNewCreator()...{};


    };




    template <class T>


    struct MallocCreator




    ...{


        static T* Create()




        ...{


            T* buf = (T*)std::malloc(sizeof(T));


            if ( !buf )




            ...{


                return 0;


            }


            return buf;


        }


    protected:




        ~MallocCreator()...{};


    };




    template <class T>


    struct ProtypeCreator 




    ...{


    public:


        T* Create()




        ...{




            return /**//*pPrototype_ ? pPrototype_->Clone() :*/ 0;


        }






        T* GetPrototype() ...{ return pPrototype_; }






        void SetPrototype(T* pObj) ...{ pPrototype_ = pObj; }


    protected:




        ~ProtypeCreator()...{};


    private:


        T* pPrototype_;


    };




    template<


            class T,


            template <class> class CreatePolicy = OpNewCreator


            >


    class CommonObj:public CreatePolicy<T>




    ...{


    public:


        CommonObj()




        ...{


            CreatePolicy<T>::Create();


        }






        ~CommonObj()...{}




        void Test()




        ...{


            std::cout<<"Hello World";


        }


    protected:


    };


}












int _tmain(int argc, _TCHAR* argv[])




...{


    typedef SHFTest::CommonObj<int,SHFTest::ProtypeCreator> myProtypeObj;


    myProtypeObj Testobj1;


    Testobj1.Test();




    typedef SHFTest::CommonObj<int> myObj;


    myObj Testobj2;


    Testobj2.Test();




    return 0;


}

以上是个人读后感的,有什么不对的地方希望大家指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class c++ struct 框架 工作