Jump to content

Curiously recurring template pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Dave abrahams (talk | contribs) at 03:50, 20 April 2006. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

A term due to Coplien [1], who had observed it in some of the earliest C++ template code. In the Curiously Recurring Template Pattern (CRTP), a base class template is instantiated with a derived class type as its template parameter:

Example

 // The Curiously Recurring Template Pattern (CRTP)
 struct derived : base<Derived>
 {
     // ...
 };

Typically, the base class template will take advantage of the fact that member function bodies 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();
          // ...
     }
 };
 // ...
 struct my_derived : base<my_derived>
 {
      void implementation() { ... }
 };

This technique achieves a similar effect to the use of virtual functions, without the costs (and some flexibility) of dynamic polymorphism.

See Also

Barton-Nackman Trick

References

  • Coplien, James O. (1995, February). "Curiously Recurring Template Patterns". C++ Report: 24–27. {{cite journal}}: Check date values in: |year= (help)CS1 maint: year (link)