欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

template应用之Policies和Policy Classes

发布时间:2023/12/16 编程问答 71 豆豆
生活随笔 收集整理的这篇文章主要介绍了 template应用之Policies和Policy Classes 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Policies和Policy Classes

什么是Policy?

Policy定义一个class或class template的接口,该接口由内隐型别定义( inner type definition) 、成员函数和成员变量之一或全部组成。

例子

声明Policy:policy_Create()可以理解为一种语法约束:

  • 要有Create()接口
  • Create()返回值必须是T*
  • template<typename Policy> struct Creator {explicit Creator(Policy& policy) : policy_(policy)T* Create(){return policy_.Create();}private:Policy& policy_; }

    实现Policy
    声明Policy约束实现Policy必须实现Create接口,并满足Create接口协议。至于如何实现Create接口,则可以有很多的技术选择,如下代码有通过new、malloc + Placement new、Prototype等实现。
    这也是面向接口编程的一种方式:实现不应该依赖于具体细节,应该依赖于接口(抽象)。

    template<typename T> struct OpNewCreator {static T* Create(){return new T;} };template<typename T> struct MallocCreator {static T* create(){void* buf = std::malloc(sizeof(T));if (!buf) return nullptr;return new(buf) T;} };temp1ate<typename T> struct PrototypeCreator {PrototypeCreator(T* pObj = nullptr) : pPrototype_(pObj){}T* Create(){return pPrototype_ ? pPrototype_->Clone() : nullptr;}T* GetPrototype() { return pPrototype_; }void setPrototype (T* pObj) { pPrototype_ = p0bj; } private:T* pPrototype_; };

    通过上述Policy和Policy Classes可以组合满足多种需求:

  • Creator<OpNewCreator<T>>
  • Creator<MallocCreator<T>>
  • Creator<PrototypeCreator<T>>
  • 更为重要的是,Policy与Policy Classes是松散的,没有接口继承那种强绑定关系。只要满足Policy约定就可以自由装配(组合)。
    这就是template 组合的魅力!!!
    当然由template特性决定,Policy是编译期的静态绑定,不适用于动态连结和二进位接口。
    从这点看,Policy与传统的接口具有一定的互补关系。

    Policy支持用户扩展

    通过Template和继承结合,继承Policy的类可以获得Policy特有的类信息。实现类可以根据需要定制这些信息,这种好处是使用者决定用什么,而不是库决定使用者用什么,具有更多的灵活性。

    Policy的析构函数

  • 不能使用虚析构函数,虚表指针会带来内存和性能上的负担
  • 不能是private或protected派生,会失去Policy的部分特性
  • 轻量办法,Policy类提供protected析构函数,保证只能子类使用,以现在向上转型带来的资源释放问题
  • struct OpNewCreator {template <class T>static T* Create(){return new T;} protected :~OpNewCreator() { } };

    不完整具现化

    如果class template有一个成员函数未曾被用到,它就不会被编译器具体实现出来。编译器不理会它,甚至也许不会为它进行语法检验。

    如何获得Policy类

    将参与class行为的设计鉴别出来并命名之。任何事情只要能以一种以上的方法解决,都应该被分析出来,并从class中移出来成为policy。
    当你将class分解为policies 时,找到正交分解很重要。正交分解会产生一些彼此完全独立的policies。

    Policies机制

    templates + 多重继承

    template <class T,template<class> class CheckingPolicy,template <class> class ThreadingModel,template <class> class Storage = Defau1tSmartPtrStorage > class SmartPtr : public CheckingPolicy<T>, public ThreadingModel<T>, public Storage<T> { // ... };

    由Policies设计的class的优势

  • 扩展性+客户定制
  • 环绕着policies而设计出来的classes,支持“可扩充的行为”和“优雅的机能削减”。由于采用“public继承”之故,policy得以通过host class提供追加机能。而 host classes也能运用“policy提供的选择性机能”实作出更丰富的功能。如果某个选择性机能不存在,host class还是可以成功编译,前提是该选择性机能未被真正用上。

  • 可以互相混搭
  • 定制行为和定制结构
  • class拆分policies准则

    第一,将class内的“设计决定”局部化、命名、分离出来;
    第二,找出正交的policies-——也就是彼此之间无交互作用、可独立更动的policies。

    总结

    以上是生活随笔为你收集整理的template应用之Policies和Policy Classes的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。