CAUTION!

CAUTION! DANGER ZONE ahead. Beware of misinformation on the open internet. Contents of the site are mere opinions and are not always facts!

Friday, January 16, 2015

CRTP

CRTP: Curiously Recurring Template Pattern.

let us consider a scenario which requires the pattern. I would like to design an abstract class to be implemented by the sub classes. Along with my API's, I have added some common members that every subclass must have - say, an id. And I would like to have a static member in each of my sub classes.

Approach: i added a static member in my abstract class. I have declared my static member in the class header and defined in the class cpp file.

problems:
1. All the translation units implementing the abstract class must also include the class cpp file for compilation or include the static library for the abstract interface.

2. The static member is shared accross all the instances of all the sub class types. but I would like to share one static member amongst all the instances of each sub class type.

CRTP to the rescue...

The abstract class is templated for the sub class type. One static member is created for each abstract class instantiation by the sub classes. Thus, the abstract class defines one static member for each sub class.

template<typename _subClass>
class AbstractClass
{

    static int m_staticMember;
    //...    

};

template<typename _subClass>
int AbstractClass<_subClass>::m_staticMember;