Skip to content

Curiously Recurring Template Pattern

Curiously Recurring Template Pattern

The Curiously Recurring Template Pattern is an idiom in which a class X derives from a class template Y, taking a template parameter Z, where Y is instantiated with Z=X.

CRTP may be used to implement "compile-time polymorphism", when a base class exposes an interface, and derived classes implement such interface.

1
2
3
4
template <typename derived> class shape {
  public:
    virtual derived clone() { return static_cast<derived>(*this); };
};

1
2
3
4
5
6
7
class square : public shape<square> {
  public:
    square() = default;
    explicit square(const shape &){};
    // CRTP: Clone can return a square even though it's derived from shape
    square clone() override { return *this; }
};

1
2
square a;
square b = a.clone();

1
2
3
std::cout << "The square has been cloned as a real square" << '\n';
std::cout << "&a: " << &a << '\n';
std::cout << "&b: " << &b << '\n';

Share Snippets