Site Tools


wiki:cpp-crtp

Table of Contents

C++ CRTP

CRTP (Curiously Recurring Template Pattern) is a static polymorphism technique where a derived class passes itself as a template parameter to its base class. This enables zero-overhead polymorphism without virtual functions by allowing the base to call derived implementations at compile time.

Use CRTP when you need polymorphic behavior without the runtime cost of virtual function calls.

Example

This example shows how CRTP allows a base class to call derived methods without virtual functions.

// compile: g++ -o crtp crtp.cpp
// run: ./crtp
// description: static polymorphism via CRTP without virtual dispatch
 
#include <iostream>
 
template <typename Derived>
class Shape {
public:
    void draw() {
        static_cast<Derived*>(this)->drawImpl();
    }
};
 
class Circle : public Shape<Circle> {
public:
    void drawImpl() { std::cout << "Drawing circle\n"; }
};
 
class Square : public Shape<Square> {
public:
    void drawImpl() { std::cout << "Drawing square\n"; }
};
 
int main() {
    Circle c;
    c.draw();
 
    Square s;
    s.draw();
 
    return 0;
}
wiki/cpp-crtp.md · Last modified: (external edit)