パラメータ化継承
テンプレート引数で基本クラスを指定する手法らしい。発想としてはデコレーターパターンに近いような気がする。ここでは文字列の出力を太字・イタリック・あるいはその合成に指定できるようなサンプルコードを書く。
#include <string> #include<iostream> using namespace std; //ベースとなるクラス基本的な出力を担当 class Plain { public : string Show(const string & x){return x;} }; class Twice { public : string Show(const string & x){return (x + " " + x);} }; //基本出力を<b></b>タグで挟む template<class Base> class Bold : public Base { public : string Show(const string & x){return "<b>" + Base::Show(x) + "</b>";} }; //基本出力を<i></i>タグで挟む template<class Base> class Italic : public Base { public : string Show(const string & x){return "<i>" + Base::Show(x) + "</i>";} }; //メイン関数 int main() { string x = "Hello, world"; Bold<Plain> bold; Italic<Plain> italic; //ベースクラスはネスト可能 Bold<Italic<Plain>> bold_italic; //Interfaceさえ揃っていれば異なるクラス(Twice)も使用できる Bold<Twice> bold2; //出力 cout << bold.Show(x) << endl; cout << italic.Show(x) << endl; cout << bold_italic.Show(x) << endl; cout << bold2.Show(x) << endl; return 0; }
実行結果は
<b>Hello, world</b> <i>Hello, world</i> <b><i>Hello, world</i></b> <b>Hello, world Hello, world</b>