Curiously Recurring Template Pattern
From cppreference.net
El
Curiously Recurring Template Pattern
es un patrón en el cual una clase
X
deriva de una plantilla de clase
Y
, tomando un parámetro de plantilla
Z
, donde
Y
se instancia con
Z
=
X
. Por ejemplo,
template<class Z> class Y {}; class X : public Y<X> {};
Ejemplo
CRTP puede utilizarse para implementar "polimorfismo en tiempo de compilación", cuando una clase base expone una interfaz y las clases derivadas implementan dicha interfaz.
Ejecutar este código
#include <cstdio> #ifndef __cpp_explicit_this_parameter // Traditional syntax template <class Derived> struct Base { void name() { static_cast<Derived*>(this)->impl(); } protected: Base() = default; // prohibits the creation of Base objects, which is UB }; struct D1 : public Base<D1> { void impl() { std::puts("D1::impl()"); } }; struct D2 : public Base<D2> { void impl() { std::puts("D2::impl()"); } }; #else // C++23 deducing-this syntax struct Base { void name(this auto&& self) { self.impl(); } }; struct D1 : public Base { void impl() { std::puts("D1::impl()"); } }; struct D2 : public Base { void impl() { std::puts("D2::impl()"); } }; #endif int main() { D1 d1; d1.name(); D2 d2; d2.name(); }
Salida:
D1::impl() D2::impl()
Véase también
Funciones miembro de objeto explícito (deduciendo
this
)
(C++23)
|
|
|
(C++11)
|
permite a un objeto crear un
shared_ptr
que hace referencia a sí mismo
(plantilla de clase) |
|
(C++20)
|
plantilla de clase auxiliar para definir una
view
, usando el
patrón de plantilla recurrente curioso
(plantilla de clase) |
Enlaces externos
| 1. | ¿Reemplazar CRTP con concepts? — Blog de Sandor Drago |
| 2. | The Curiously Recurring Template Pattern (CRTP) — Blog de Sandor Drago |
| 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 |