More C++ Idioms/Curiously Recurring Template Pattern

From Wikibooks, open books for an open world
Jump to: navigation, search

Curiously Recurring Template Pattern[edit]

Intent[edit]

Specialize a base class using the derived class as a template argument.

Also Known As[edit]

  • CRTP
  • Mixin-from-above

Motivation[edit]

To extract out a type independent but type customizable functionality in a base class and to mix-in that interface/property/behavior into a derived class, customized for the derived class.

Solution and Sample Code[edit]

In CRTP idiom, a class T, inherits from a template that specializes on T.

class T : public X<T> {};

This is valid only if the size of X<T> can be determined independently of T. Typically, the base class template will take advantage of the fact that member function bodies (definitions) are not instantiated until long after their declarations, and will use members of the derived class within its own member functions, via the use of a static_cast, e.g.:

  template <class Derived>
  struct base
  {
      void interface()
      {
          // ...
          static_cast<Derived*>(this)->implementation();
          // ...
      }
 
      static void static_interface()
      {
          // ...
          Derived::static_implementation();
          // ...
      }
 
      // The default implementation may be (if exists) or should be (otherwise) 
      // overriden by inheriting in derived classes (see below)
      void implementation();
      static void static_implementation();
  };
 
  // The Curiously Recurring Template Pattern (CRTP)
  struct derived_1 : base<derived_1>
  {
      // This class uses base variant of implementation
      //void implementation();
 
      // ... and overrides static_implementation
      static void static_implementation();
  };
 
  struct derived_2 : base<derived_2>
  {
      // This class overrides implementation
      void implementation();
 
      // ... and uses base variant of static_implementation
      //static void static_implementation();
  };

Known Uses[edit]

Barton-Nackman trick

Related Idioms[edit]

References[edit]

Curiously Recurring Template Pattern on Wikipedia