Jump to content

Curiously recurring template pattern: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
inline references
Line 1: Line 1:
The '''curiously recurring template pattern''' ('''CRTP''') is a [[C++]] idiom in which a class <code>X</code> derives from a class template instantiation using <code>X</code> itself as template argument. The name of this idiom was coined by [[Jim Coplien]]{{ref|Coplien}}, who had observed it in some of the earliest [[C++]] template code.
The '''curiously recurring template pattern''' ('''CRTP''') is a [[C++]] idiom in which a class <code>X</code> derives from a class template instantiation using <code>X</code> itself as template argument. The name of this idiom was coined by [[Jim Coplien]]<ref>{{cite journal | author=Coplien, James O. | title=Curiously Recurring Template Patterns | journal=C++ Report | year=1995, February | pages=24–27}}</ref>, who had observed it in some of the earliest [[C++]] template code.


== General form ==
== General form ==
Line 16: Line 16:
</source>
</source>


Some use cases for this pattern are [[Template metaprogramming#Static_polymorphism|static polymorphism]], and other metaprogramming techniques such as those described by Alexandrescu{{ref|Alexandrescu}} in [[Modern C++ Design]].
Some use cases for this pattern are [[Template metaprogramming#Static polymorphism|static polymorphism]], and other metaprogramming techniques such as those described by [[Andrei Alexandrescu|Alexandrescu]] in [[Modern C++ Design]] <ref>[[Andrei Alexandrescu]]: ''[[Modern C++ Design]]: Generic Programming and Design Patterns Applied'', Addison-Wesley, ISBN 3-8266-1347-3</ref>.


== Static polymorphism ==
== Static polymorphism ==
Line 92: Line 92:
==In other languages==
==In other languages==


The CRTP makes an appearance in the [[Java language|Java programming language]] standard library where the [[Enumerated type|Enum]] class is defined as <code>Enum&lt;T extends Enum&lt;T&gt;&gt;</code>. Java programmers use the CRTP in practice when they write a comparable class: <code>class X implements Comparable&lt;X&gt;</code>.
The CRTP makes an appearance in the [[Java language|Java programming language]] standard library where the [[Enumerated type|Enum]] class is defined as <code>Enum&lt;T extends Enum&lt;T&gt;&gt;</code>. Java programmers use the CRTP in practice when they write a comparable class: <code>class X implements Comparable&lt;X&gt;</code>.


==See also==
==See also==
Line 99: Line 99:


==References==
==References==
<references/>
* {{note|Coplien}}{{cite journal | author=Coplien, James O. | title=Curiously Recurring Template Patterns | journal=C++ Report | year=1995, February | pages=24–27}}
<!-- can somebody inline this reference in a relevant place?
* {{note|Alexandrescu}}[[Andrei Alexandrescu]]: ''[[Modern C++ Design]]: Generic Programming and Design Patterns Applied'', Addison-Wesley, ISBN 3-8266-1347-3
* {{note|Abrahams}}[[David Abrahams]], Aleksey Gurtovoy: ''C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond'', Addison-Wesley, ISBN 0-321-22725-5
* {{note|Abrahams}}[[David Abrahams]], Aleksey Gurtovoy: ''C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond'', Addison-Wesley, ISBN 0-321-22725-5
-->


[[Category:Software design patterns]]
[[Category:Software design patterns]]

Revision as of 14:34, 17 July 2008

The curiously recurring template pattern (CRTP) is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument. The name of this idiom was coined by Jim Coplien[1], who had observed it in some of the earliest C++ template code.

General form

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

Some use cases for this pattern are static polymorphism, and other metaprogramming techniques such as those described by Alexandrescu in Modern C++ Design [2].

Static polymorphism

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, or simply a cast e.g.:

template <class Derived> struct Base
{
    void interface()
    {
        // ...
        static_cast<Derived*>(this)->implementation();
        // ...
    }

    static void static_func()
    {
        // ...
        Derived::static_sub_func();
        // ...
    }
};

struct Derived : Base<Derived>
{
    void implementation();
    static void static_sub_func();
};

This technique achieves a similar effect to the use of virtual functions, without the costs (and some flexibility) of dynamic polymorphism. This particular use of the CRTP has been called "simulated dynamic binding" by some[3]. This pattern is used extensively in the Windows ATL and WTL libraries.

To elaborate on the above example, consider a base class with no virtual functions. Whenever the base class calls another member function, it will always call its own base class functions. When we inherit from this class, a derived class, we inherit all the member variables and member functions that weren't overridden (no constructors or destructors, of course, either). If the derived class calls an inherited function that then calls another member function, that function will never call any derived or overridden member functions in the derived class. As a result of this behavior, most C++ programmers define member functions as virtual to avoid this problem.

However, if base class member functions use the CRTP pattern for all member function calls, the overridden functions in the derived class will get selected at compile time. This effectively emulates the virtual function call system at compile time without the costs in size or function call overhead (VTBL structures, and method lookups, multiple-inheritance VTBL machinery) and the slight disadvantage of not being able to do this choice at runtime.

Object counter

The main purpose of an object counter is retrieving statistics of object creation and destruction for a given class. This can be easily solved using CRTP:

template <typename T>
struct counter
{
    counter()
    {
        objects_created++;
        objects_alive++;
    }

    virtual ~counter()
    {
        --objects_alive;
    }
    static int objects_created;
    static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );

class X : counter<X>
{
    // ...
};

class Y : counter<Y>
{
    // ...
};

Each time an object of class X is created, the constructor of counter<X> is called, incrementing both the created and alive count. Each time an object of class X is destroyed, the alive count is decremented. In this example, none of the functionality in the template uses the template parameter, and it is only used as a way of creating different static counters for different classes. Remember that each instantiation of a template with a type argument is a class of itself, and thus the static counter attributes in the counter template are different offering separated counters for X and Y classes.

In other languages

The CRTP makes an appearance in the Java programming language standard library where the Enum class is defined as Enum<T extends Enum<T>>. Java programmers use the CRTP in practice when they write a comparable class: class X implements Comparable<X>.

See also

References

  1. ^ Coplien, James O. (1995, February). "Curiously Recurring Template Patterns". C++ Report: 24–27. {{cite journal}}: Check date values in: |year= (help)
  2. ^ Andrei Alexandrescu: Modern C++ Design: Generic Programming and Design Patterns Applied, Addison-Wesley, ISBN 3-8266-1347-3
  3. ^ http://www.pnotepad.org/devlog/archives/000083.html