January 2019
Intermediate to advanced
384 pages
11h 50m
English
But, what if you still don't want to pay the price for polymorphism? One possibility is to switch to static polymorphism. The curiously recurring template pattern (CRTP) is one of the older template techniques popularized by Jim Coplien in the 90s. CRTP defines a kind of mix-in, which adds some functionality to a given class but doesn't use virtual functions for that, as in the following example:
template<class T>class OracleBase{ // within base we can use members of derived class T! int whatsTheAnswer() const { return static_cast<T>(this)->getAnswer() * 2; } };class Oracle1: public OracleBase<Oracle1>{ int getAnswer() const { return 22; }} o1;class Oracle2: public OracleBase<Oracle2>{ int getAnswer() const { ...Read now
Unlock full access