1章 1.6 ポリシーの拡張 - Modern C++ Designを読む(2)
Hello World Managerクラスは Create Policy を継承します。
そのとき要求しているのは T* Create()という関数だけですが、特定のPolicy においてあえて拡張することが可能という話。
PrototypeCreatorクラスは Create()以外に、SetPrototype(), GetPrototype()を提供してる。
template <class T>
struct PrototypeCreator
{
PrototypeCreator(T* obj = 0) : prototype_(obj) {}
T* Create()
{
return prototype_ ? prototype_ : 0;
}
T* GetPrototype() { return prototype_; }
void SetPrototype(T* obj) { prototype_ = obj; }
private:
T* prototype_;
};なのでユーザーが数あるPolicyの中から PrototypeCreator を利用することを選べば、Create以外に SetPrototype 利用可能になります。
HelloWorldManager<PrototypeCreator> manager; HelloWorld* h = manager.Create(); h->say(); manager.SetPrototype(NULL); // ここ
ポイントは、SetPrototypeの拡張がコンパイル時にチェックされることかな。
例えば PrototypeCreator の替わりに OpNewCreator を利用すると
main.cpp:63: error: ‘class HelloWorldManager<OpNewCreator>’ has no member named ‘SetPrototype’
コンパイル時に怒られます。なるほどね。
Modern C++ Design―ジェネリック・プログラミングおよびデザイン・パターンを利用するための究極のテンプレート活用術
posted with amazlet on 06.11.21
