Friday, September 11, 2009

Episode Eight: The Curious Case of Recurring Template Pattern

The curiously recurring template pattern (CRTP) is an idiom in which a class X derives from a class template instantiation using X itself as template argument. It splits generic and concrete functionality by delegating to its derived class. This works because X is an incomplete type at the point of template instantiation, and it only works when the declaration of the base template does not use X as a complete type. Member function definitions, on the other side, are instantiated long after their declarations, allowing use of members of the derived class via the use of a static_cast.



One of its notable uses is to achieve static polymorphism, which is a compile time polymorphism and thus does not have to pay the overhead associated with virtual functions (namely, the overhead of a virtual function call and the generation of typeids). Consider the following example, adapted from Wikipedia's example on C++ (dynamic) polymorphism [1]:
template< Derived >
class Animal
{
string talk(){ return static_cast< Derived* >( this )->talk(); }
};

class Cat : public Animal< Cat >
{
string talk() { return "Meow!"; }
};

class Dog : public Animal< Dog >
{
string talk() { return "Arf! Arf!"; }
};
Note that Animal< Cat > and Animal< Dog > are two unrelated classes, this means there is no common base class between a Cat and a Dog. Dynamic polymorphism can be reintroduced by making Animal inherit from an AnyAnimal class which defines `virtual string talk() = 0;`, or non-intrusively by means of type erasure.

[1] Wikipedia - Polymorphism in object-oriented programming

No comments:

Post a Comment