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

Curiously Recurring Template Pattern 은 클래스 X 가 템플릿 클래스 Y 를 상속하는데, 이때 템플릿 매개변수 Z 를 사용하며, Y Z = X 로 인스턴스화되는 관용구입니다. 예를 들어,

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

예제

CRTP는 기본 클래스가 인터페이스를 노출하고 파생 클래스가 해당 인터페이스를 구현할 때 "컴파일 타임 다형성"을 구현하는 데 사용될 수 있습니다.

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

출력:

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

참고 항목

명시적 객체 멤버 함수 ( this 추론) (C++23)
객체가 자신을 참조하는 shared_ptr 을 생성할 수 있도록 함
(클래스 템플릿)
view 를 정의하기 위한 도우미 클래스 템플릿, curiously recurring template pattern 사용
(클래스 템플릿)

외부 링크

1. CRTP를 개념(concepts)으로 대체할까? — Sandor Drago의 블로그
2. 신기하게 반복되는 템플릿 패턴 (CRTP) — Sandor Drago의 블로그
3. 신기하게 반복되는 템플릿 패턴 (CRTP) - 1 — Fluent { C ++ }
4. CRTP가 코드에 가져다주는 것 - 2 — Fluent { C ++ }
5. CRTP 구현을 위한 도우미 - 3 — Fluent { C ++ }
6. 신기하게 반복되는 템플릿 패턴 (CRTP)이란 무엇인가 — 스택오버플로우(SO)