The art of template and inheritance-the unique recursive template mode (CRTP) and recursive crtp

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.