This basic design — having clients call private virtual functions indirectly through public non-virtual member functions — is known as the non-virtual interface (NVI) idiom
class GameCharacter {
public: int healthValue() const // derived classes do not redefine { // this — see Item 36 ... // do "before" stuff — see below int retVal = doHealthValue(); // do the real work ... // do "after" stuff — see below return retVal; } ... private: virtual int doHealthValue() const // derived classes may redefine this { ... // default algorithm for calculating } // character's health };
|
we replace the use of a function pointer (such as healthFunc) with an object of type TR1::function. As explains, such objects may hold any callable entity (i.e., function pointer, function object, or member function pointer) whose signature is compatible with what is expected.
int defaultHealthCalc(const GameCharacter& gc); // as before
typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc;
|
阅读(670) | 评论(0) | 转发(0) |