Skip to main content

Posts

Showing posts from January, 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/stru