Without referring to a book, can anyone please provide a good explanation for CRTP (curiously recurring template pattern) with a code example?
Without referring to a book, can anyone please provide a good explanation for CRTP
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In short, CRTP is when a class
Ahas a base class which is a template specialization for the classAitself. E.g.It is curiously recurring, isn’t it? 🙂
Now, what does this give you? This actually gives the
Xtemplate the ability to be a base class for its specializations.For example, you could make a generic singleton class (simplified version) like this
Now, in order to make an arbitrary class
Aa singleton you should do thisHowevry, CRTP is not necessary in this case, see as follow:
So you see? The singleton template assumes that its specialization for any type
Xwill be inherited fromsingleton<X>and thus will have all its (public, protected) members accessible, including theGetInstance! There are other useful uses of CRTP. For example, if you want to count all instances that currently exist for your class, but want to encapsulate this logic in a separate template (the idea for a concrete class is quite simple – have a static variable, increment in ctors, decrement in dtors). Try to do it as an exercise!Yet another useful example, for Boost (I am not sure how they have implemented it, but CRTP will do too).
Imagine you want to provide only operator
<for your classes but automatically operator==for them!you could do it like this:
or implement within the template scope without casting
Now you can use it like this
Now, you haven’t provided explicitly operator
==forApple? But you have it! You can writeThis could seem that you would write less if you just wrote operator
==forApple, but imagine that theEqualitytemplate would provide not only==but>,>=,<=etc. And you could use these definitions for multiple classes, reusing the code!CRTP is a wonderful thing 🙂 HTH