The art of template and inheritance-the unique recursive template mode (CRTP) and recursive crtp
1. What is the unique Template recursive Pattern of CRTP (Curiously Recurring Template Pattern )?Pass the derived class itself as a template parameter to the base class.Template <typename T> class BaseT {}; class D: public BaseT <D >{}; class D is a non-dependent base class, not a template. (1) The parameter (T) of the inherited class template (BaseT) can beTemplate parameters, Template <typename T> class BaseT {}; template <typename T> class D: public BaseT <D <T >{}; (2) the parameter (T) of the inherited class template (BaseT) can beTemplateTypename <template <typename> class T>Class BaseT {}; Template <typename T>Class D: public BaseT <D> {}; 2. A simple application of CRTP is to record the total number of constructed class objects.
# Include <stddef. h>
# Include <iostream>
Template <typename CountedType>
Class ObjectCounter {
Static size_t count;
Protected:
ObjectCounter () {++ObjectCounter <CountedType>: count;}// Declare it as protected to prevent object generation. Only inherited objects are allowed.
ObjectCounter (constObjectCounter <CountedType>&) {++ObjectCounter <CountedType>: count;}
~ ObjectCounter () {-- count ;}
Public:
StaticSize_t getCount () {returnObjectCounter <CountedType>: count;}// As a static function, Class Method
};
Template <typename CountedType>
Size_t ObjectCounter <CountedType>: count = 0;
Template <typename T>
Class MyString: publicObjectCounter <MyString <T>{};// CRTP
Int main () {MyString <char> s1, s2; MyString <wchar_t> ws; std: cout <"MyString <char >:" <MyString <char> :: getCount () <std: endl; // output 2 std: cout <"MyString <wchar_t>:" <MyString <wchar_t>: getCount () <std: endl; // output 1} EDIT: Claruarius. For more information, see the source.