Effective C++ Item 35 ― 2009年08月20日 11時11分47秒
- 仮想関数の代用としては NVI 慣用句を始めとした各種のデザインパターンが有効だ。
- メンバ関数を非メンバ関数にすることの欠点は、メンバ変数へのアクセスをなくす事だ。
- tr1::function は汎用関数ポインタとして用いる事が出来る。
NVI は non-virtual interface idiom の略。NVI の例。
class GameCharacter { public: int healthValue() const { ... int retVal = doHealthValue(); ... return retVal; } private: virtualint doHealthValue() const{...} };
直接、又は tr1::function を用いた関数ポインタの例。
tr1::function を用いた技法は型の自動変換が行なわれるので、強制的に型を縛り付ける関数ポインタよりも柔軟に使うことが出来る。class GameCharacter; int defaultHealthCalc(const GameCHaracter& gc); class GameCharacter { public: typedef std::tr1::function
HealthCalcFunc; explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc): healthFunc(hcf){} private: HealthCalcFunc healthFunc; };
二つのクラスに分けて各々で継承を行なう典型的なデザインパターンの方法もある。
最近のコメント