0
点赞
收藏
分享

微信扫一扫

template应用之Policies和Policy Classes

pipu 2022-03-14 阅读 27

Policies和Policy Classes

什么是Policy?

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

例子

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

  1. 要有Create()接口
  2. 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可以组合满足多种需求:

  1. Creator<OpNewCreator<T>>
  2. Creator<MallocCreator<T>>
  3. Creator<PrototypeCreator<T>>

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

举报

相关推荐

0 条评论