Namespaces
Variants

Curiously Recurring Template Pattern

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

Das Curiously Recurring Template Pattern ist ein Idiom, bei dem eine Klasse X von einer Klassentemplate Y abgeleitet wird, wobei ein Template-Parameter Z verwendet wird, wobei Y instanziiert wird mit Z = X . Zum Beispiel,

template<class Z>
class Y {};
class X : public Y<X> {};

Beispiel

CRTP kann verwendet werden, um "Compile-Time-Polymorphie" zu implementieren, wenn eine Basisklasse eine Schnittstelle bereitstellt und abgeleitete Klassen diese Schnittstelle implementieren.

#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();
}

Ausgabe:

D1::impl()
D2::impl()

Siehe auch

Explizite Objekt-Memberfunktionen (Ableitung von this ) (C++23)
ermöglicht einem Objekt, einen shared_ptr zu erstellen, der auf sich selbst verweist
(Klassentemplate)
Hilfsklassentemplate zur Definition einer view unter Verwendung des Curiously Recurring Template Pattern
(Klassentemplate)

Externe Links

1. CRTP durch Konzepte ersetzen? — Sandor Dragos Blog
2. Das Curiously Recurring Template Pattern (CRTP) — Sandor Dragos Blog
3. Das Curiously Recurring Template Pattern (CRTP) - 1 — Fluent { C ++ }
4. Was das CRTP Ihrem Code bringen kann - 2 — Fluent { C ++ }
5. Eine Implementierungshilfe für das CRTP - 3 — Fluent { C ++ }
6. Was ist das Curiously Recurring Template Pattern (CRTP) — SO