More C++ Idioms/Curiously Recurring Template Pattern

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

Curiously Recurring Template Pattern
[edit | edit source]

Intent[edit | edit source]

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

Also Known As[edit | edit source]

  • CRTP
  • Mixin-from-above
  • Static polymorphism
  • Simulated dynamic binding
  • Upside-down Inheritance

Motivation[edit | edit source]

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 | edit source]

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) 
      // overridden 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 | edit source]

Barton-Nackman trick

Related Idioms[edit | edit source]

References[edit | edit source]

Curiously Recurring Template Pattern on Wikipedia