ArticleslgStudy

computer science

Curiously recurring template pattern

Curiously recurring template pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Curiously recurring template pattern rather than just read about it. In short: The curiously recurring template pattern (CRTP) is an idiom in which a class derives from a class template instantiation using itself as a template parameter. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

Key takeaways

  • Curiously recurring template pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Curiously recurring template pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Curiously recurring template pattern from memory before moving on to harder problems.

Reference excerpt

The curiously recurring template pattern (CRTP) is an idiom in which a class derives from a class template instantiation using itself as a template parameter. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

History The technique was formalized in 1989 as "F-bounded quantification." The name "CRTP" was independently coined by Jim Coplien in 1995, who had observed it in some of the earliest C++ template code as well as in code examples that Timothy Budd created in his multiparadigm language Leda. It is sometimes called "Upside-Down Inheritance" due to the way it allows class hierarchies to be extended by substituting different base classes. The Microsoft Implementation of CRTP in Active Template Library (ATL) was independently discovered, also in 1995, by Jan Falkin, who accidentally derived a base class from a derived class. Christian Beaumont first saw Falkin's code and initially thought it could not compile in the Microsoft compiler available at the time. Following the revelation that it did work, Beaumont based the entire ATL and Windows Template Library (WTL) design on this mistake.

General form

One use case for this pattern is static polymorphism. It also figures prominently in the C++ implementation of the Data, Context, and Interaction paradigm. In addition, CRTP is used by the C++ standard library to implement the std::enable_shared_from_this functionality. In Java and C#, CRTP can be done using recursive generics, with the base class being a generic parameter inheriting from itself:

For example, java.lang.Enum<E>, a class which all enums inherit from, has the signature public abstract class Enum<E extends Enum<E>> extends Object implements Constable, Comparable<E>, Serializable. Rust, however, due to not using inheritance, avoids CRTP entirely, and achieves its results using the Self keyword.

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 cast; e.g.:

In the above example, the function Base<Derived>::call(), though declared before the existence of the struct Derived is known by the compiler (i.e., before Derived is declared), is not actually instantiated by the compiler until it is actually called by some later code which occurs after the declaration of Derived (not shown in the above example), so that at the time the function call is instantiated, the declaration of Derived::implementation() is known. 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. 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 derive a class from this base class, we inherit all the member variables and member functions that were not overridden (no constructors or destructors). If the derived class calls an inherited function which then calls another member function, then that function will never call any derived or overridden member functions in the derived class. However, if base class member functions use CRTP for all member function calls, the overridden functions in the derived class will be 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) at the disadvantage of not being able to make 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:

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. Counter<X> and Counter<Y> are two separate classes and this is why they will keep separate counts of Xs and Ys. In this example of CRTP, this distinction of classes is the only use of the template parameter (T in Counter<T>) and the reason why we cannot use a simple un-templated base class.

Polymorphic chaining Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results. When the named parameter object pattern is applied to an object hierarchy, things can go wrong. Suppose we have such a base class:

Prints can be easily chained:

However, if we define the following derived class:

we "lose" the concrete class as soon as we invoke a function of the base:

This happens because 'print' is a function of the base – 'Printer' – and then it returns a 'Printer' instance. The CRTP can be used to avoid such problem and to implement "Polymorphic chaining":

Polymorphic copy construction When using polymorphism, one sometimes needs to create copies of objects by the base class pointer. A commonly used idiom for this is adding a virtual clone function that is defined in every derived class. The CRTP can be used to avoid having to duplicate that function or other similar functions in every derived class.

This allows obtaining copies of squares, circles or any other shapes by shapePtr->clone().

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Curiously recurring template pattern

Start with the simplest possible case. Write down what Curiously recurring template pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Curiously recurring template pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Curiously recurring template pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Curiously recurring template pattern

In research
Curiously recurring template pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Curiously recurring template pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Curiously recurring template pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Curiously recurring template pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Curiously recurring template pattern” →

How to study Curiously recurring template pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Curiously recurring template pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Curiously recurring template pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Curiously recurring template pattern in simple terms?

The curiously recurring template pattern (CRTP) is an idiom in which a class derives from a class template instantiation using itself as a template parameter. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

Why does Curiously recurring template pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Curiously recurring template pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Curiously recurring template pattern.

Tags

  • C++
  • Software design patterns

Keep exploring