From cppreference.com
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. For example,
template<classZ>classY{};classX:publicY<X>{};Example
CRTP may be used to implement "compile-time polymorphism", when a base class exposes an interface, and derived classes implement such interface.
Run this code
#include<cstdio>#ifndef __cpp_explicit_this_parameter // Traditional syntaxtemplate<classDerived>structBase{voidname(){static_cast<Derived*>(this)->impl();}protected:Base()=default;// prohibits the creation of Base objects, which is UB};structD1:publicBase<D1>{voidimpl(){std::puts("D1::impl()");}};structD2:publicBase<D2>{voidimpl(){std::puts("D2::impl()");}};#else // C++23 deducing-this syntaxstructBase{voidname(thisauto&&self){self.impl();}};structD1:publicBase{voidimpl(){std::puts("D1::impl()");}};structD2:publicBase{voidimpl(){std::puts("D2::impl()");}};#endifintmain(){D1d1;d1.name();D2d2;d2.name();}Output:
D1::impl() D2::impl() See also
External links
1.
— Sandor Drago's blog 2.
The Curiously Recurring Template Pattern (CRTP)
— Sandor Drago's blog 3.
The Curiously Recurring Template Pattern (CRTP) - 1
— Fluent{C++}4.
What the CRTP can bring to your code - 2
— Fluent{C++}5.
An implementation helper for the CRTP - 3
— Fluent{C++}6.
What is the Curiously Recurring Template Pattern (CRTP)
— SO