C++ CRTP | Curiously Recurring Template Pattern

C++ CRTP | Curiously Recurring Template Pattern

이 글의 핵심

Use CRTP for compile-time customization without virtual calls and vtables.

CRTP often appears next to other compile-time structure tricks surveyed under structural patterns #19-2 and the overview #20-2.

What is CRTP?

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

struct Derived : Base<Derived> {
    void implementation() { /* ... */ }
};

vs virtual functions

  • Virtual: dynamic dispatch, vtable, runtime cost.
  • CRTP: static dispatch, inlined, no vtable for this pattern.

Mixins

Countable widgets, comparable Point with only == and < defined, etc.—see the Korean article for full examples.

Pitfalls

  • Longer compile times, more template instances.
  • Not a substitute for runtime interfaces across shared-library boundaries.

  • Policy-based design
  • CRTP deep dive

Keywords

C++, CRTP, static polymorphism, templates, mixins