Thursday, January 05, 2006

Curiously Recurring Template Pattern (CRTP)

It is a C++ idiom in which inheritance and template type parameters are cleverly integrated to generate flexible types at compile-time. In CRTP, a template class inherits from its own template parameter. For example,

template <typename Base>
class MixinOne : public Base {};

This technique is also one of the ways of using "Mixins". Here class Mixin helps to "mix in" some useful functionality into any class type Base. For example, class Mixin can make class Base a singleton. Complete code example is here. In this case of CRTP, a hierarchy (a new class plus inheritance relationship) is created when Mixin template is instantiated. Thus hierarchy creation is differed till the instantiation of the template. This is pretty cool!

Moreover, CRTP can appear in a different fashion in which a class passes itself as a template parameter to its base class. For example,

class Derived: public MixinTwo<Derived> {};

The non-template class Derived inherits interface/structure (hopefully customized for itself) from Mixin class. In this case of CRTP, the class hierarchy is "created" when Derived class is coded unlike in the earlier case where, class hierarchy is "created" when template is instantiated.

This curious name to the idiom was given by James Coplien. Also see this for a complete example of the technique.