CG@CPPBLOG

/*=========================================*/
随笔 - 76, 文章 - 39, 评论 - 137, 引用 - 0
数据加载中……

《C++设计新思维》读书笔记(三)


 
1.5.1 运用Template Template参数实作Policy Classes

如前例,库代码host class如果已知policy class,那么可以这样描述:
1 
2 //Library code
3 template < template < class Created > class CreationPolicy >
4 class WidgetManager : public CreationPolicy<Widget>{};


因为Created只是形式引数(formal argument),不可使用,可以省略如下:
1 
2 template < template < class > class CreationPolicy >
3 class WidgetManager : public CreateionPolicy<Widget>{};


客户代码为:

1 typedef WidgetManager<OpNewCreator> MyWidgetMgr;


当WidgetManager希望在内部以相同的生成策略产生一个内部对象,那么这种template template形式不可或缺。

Policy的确能够带给WidgetManager非常大的弹性。第一,可以外部变更policies。第二,可以自定义policies。

WidgetManager的作者可以定义一些常用的policies,以“template 缺省引数”的方式提供:
1 
2 template < template < class > class CreationPolicy = OpNewCreator >
3 class WidgetManager .


1.5.2 运用Template 成员函数实作Policy Classes

我们可以把先前的Creator policy定义为一个非模板类,内部提供一个模板成员函数如下:
 1 
 2 struct OpNewCreator
 3 {
 4      template < class T >
 5      static T* Create()
 6      {
 7             return new T;
 8      }
 9 }
10 

这种方式对旧式编译期有较佳兼容性。但难以讨论、定义、实作和运用。

1.6 更丰富的Policies

在前例的Creator policy中PrototypeCreateor除了提供Create()成员函数外,还提供了GetProtoType和SetProtoType两个函数,由于WidgetManager继承了policy class,所以WidgetManager具有此两个接口,虽然它自己并没有用。

客户代码可以如此:
1 
2 typedef WidgetManager<PrototypeCreator> MyWidgetManager;
3 /////////
4 widget* pPrototype = ;
5 MyWidgetManager mgr;
6 mgr.SetPrototype(pPrototype);


使用者如果需要扩充policies,可以在不影响host class原本功能的前提下,增加接口。“哪个policy被使用”由使用者决定而非程序库自身。policies给与使用者一种能力,在型别安全的前提下扩增host class的功能。

 

posted on 2007-12-17 21:44 cuigang 阅读(379) 评论(0)  编辑 收藏 引用 所属分类: 《C++设计新思维》读书笔记


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理