c++ - What is the curiously recurring template pattern (CRTP)? -
without referring book, can please provide explanation crtp
code example?
in short, crtp when class has base class template specialization class itself. e.g.
template <class t> class x{...}; class : public x<a> {...};
it is curiously recurring, isn't it? :)
now, give you? gives x template ability base class specializations.
for example, make generic singleton class (simplified version) this
template <class actualclass> class singleton { public: static actualclass& getinstance() { if(p == nullptr) p = new actualclass; return *p; } protected: static actualclass* p; private: singleton(){} singleton(singleton const &); singleton& operator = (singleton const &); }; template <class t> t* singleton<t>::p = nullptr;
now, in order make arbitrary class a singleton should this
class a: public singleton<a> { //rest of functionality class };
so see? singleton template assumes specialization type x inherited singleton<x>
, have its(public, protected) members accessible, including getinstance
! there other useful uses of crtp. example, if want count instances exist class, want encapsulate logic in separate template (the idea concrete class quite simple - have static variable, increment in ctors, decrement in dtors). try excercise!
yet useful example, boost(i not sure how have implemented it, crtp too). imagine want provide operator < classes automatically operator == them!
you this:
template<class derived> class equality { }; template <class derived> bool operator == (equality<derived> const& op1, equality<derived> const & op2) { derived const& d1 = static_cast<derived const&>(op1);//you assume works //because know dynamic type template parameter. //wonderful, isnit it? derived const& d2 = static_cast<derived const&>(op2); return !(d1 < d2) && !(d2 < d1);//assuming derived has operator < }
now can use this
struct apple:public equality<apple> { int size; }; bool operator < (apple const & a1, apple const& a2) { return a1.size < a2.size; }
now, haven't provided explicitly operator == apple? have it! can write
int main() { apple a1; apple a2; a1.size = 10; a2.size = 10; if(a1 == a2) //the compiler won't complain! { } }
this seem write less if wrote operator == apple, imagine equality template provide not == >, >=, <= etc. , use these definitions multiple classes, reusing code!
crtp wonderful thing :) hth
Comments
Post a Comment