본문으로 건너뛰기
Previous
Next
C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화

C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화

C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화

이 글의 핵심

C++ CRTP : 정적 다형성과 컴파일 타임 최적화. CRTP란?. 왜 필요한가·기본 구조.

CRTP란? 왜 필요한가

문제 시나리오: 가상 함수의 런타임 오버헤드

문제: 가상 함수는 런타임 다형성을 제공하지만, vtable 조회 비용인라인 불가로 성능이 저하됩니다.

// 가상 함수 (런타임 다형성)
// 타입 정의
class Shape {
public:
    virtual double area() const = 0;  // vtable 조회
};
class Circle : public Shape {
public:
    double area() const override {
        return 3.14159 * radius * radius;
    }
private:
    double radius;
};
void process(const Shape& s) {
    double a = s.area();  // 런타임에 vtable 조회
}

해결: CRTP(Curiously Recurring Template Pattern)는 컴파일 타임 다형성을 제공합니다. 파생 클래스를 템플릿 인자로 받아 static_cast로 호출하므로, vtable 없이 인라인 최적화가 가능합니다.

// CRTP (컴파일 타임 다형성)
// 실행 예제
template<typename Derived>
class Shape {
public:
    double area() const {
        return static_cast<const Derived*>(this)->areaImpl();
    }
};
class Circle : public Shape<Circle> {
public:
    double areaImpl() const {
        return 3.14159 * radius * radius;
    }
private:
    double radius;
};
void process(const auto& s) {
    double a = s.area();  // 컴파일 타임에 인라인
}
// 실행 예제
flowchart TD
    subgraph virtual["가상 함수 (런타임)"]
        v1["Shape* ptr"]
        v2[ptr-area()]
        v3["vtable 조회"]
        v4["Circle area() 호출"]
    end
    subgraph crtp["CRTP (컴파일 타임)"]
        c1["ShapeCircle obj"]
        c2[obj.area()]
        c3[static_castCircle*(this)]
        c4["Circle areaImpl() 인라인"]
    end
    v1 --> v2 --> v3 --> v4
    c1 --> c2 --> c3 --> c4

1. 기본 구조

최소 CRTP

#include <iostream>
template<typename Derived>
class Base {
public:
    void interface() {
        static_cast<Derived*>(this)->implementation();
    }
};
class Derived : public Base<Derived> {
public:
    void implementation() {
        std::cout << "Derived implementation\n";
    }
};
int main() {
    Derived d;
    d.interface();  // "Derived implementation"
}

핵심: BaseDerived를 템플릿 인자로 받아, static_cast<Derived*>(this)로 파생 클래스 메서드를 호출합니다.

2. 인터페이스 강제

Shape 예제

#include <iostream>
#include <cmath>
template<typename Derived>
class Shape {
public:
    double area() const {
        return static_cast<const Derived*>(this)->areaImpl();
    }
    
    void draw() const {
        static_cast<const Derived*>(this)->drawImpl();
    }
};
class Circle : public Shape<Circle> {
public:
    Circle(double r) : radius(r) {}
    
    double areaImpl() const {
        return M_PI * radius * radius;
    }
    
    void drawImpl() const {
        std::cout << "Drawing circle with radius " << radius << '\n';
    }
    
private:
    double radius;
};
class Rectangle : public Shape<Rectangle> {
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    
    double areaImpl() const {
        return width * height;
    }
    
    void drawImpl() const {
        std::cout << "Drawing rectangle " << width << "x" << height << '\n';
    }
    
private:
    double width, height;
};
template<typename T>
void processShape(const Shape<T>& s) {
    std::cout << "Area: " << s.area() << '\n';
    s.draw();
}
int main() {
    Circle c(5.0);
    Rectangle r(4.0, 6.0);
    
    processShape(c);  // Area: 78.5398, Drawing circle...
    processShape(r);  // Area: 24, Drawing rectangle...
}

장점: CircleRectangleareaImpl(), drawImpl()을 구현하지 않으면 컴파일 에러가 발생해 인터페이스를 강제합니다.

3. 정적 카운터

객체 개수 추적

#include <iostream>
template<typename Derived>
class Counter {
public:
    Counter() { ++count; }
    Counter(const Counter&) { ++count; }
    ~Counter() { --count; }
    
    static int getCount() { return count; }
    
private:
    static inline int count = 0;
};
class Widget : public Counter<Widget> {};
class Gadget : public Counter<Gadget> {};
int main() {
    {
        Widget w1, w2;
        Gadget g1;
        std::cout << "Widgets: " << Widget::getCount() << '\n';  // 2
        std::cout << "Gadgets: " << Gadget::getCount() << '\n';  // 1
    }
    std::cout << "Widgets: " << Widget::getCount() << '\n';  // 0
    std::cout << "Gadgets: " << Gadget::getCount() << '\n';  // 0
}

핵심: 각 파생 클래스마다 독립적인 count 변수가 생성됩니다 (템플릿 인스턴스화).

4. Mixin과 CRTP

기능 조합

#include <iostream>
#include <string>
template<typename Derived>
class Printable {
public:
    void print() const {
        std::cout << static_cast<const Derived*>(this)->toString() << '\n';
    }
};
template<typename Derived>
class Comparable {
public:
    bool operator<(const Derived& other) const {
        return static_cast<const Derived*>(this)->compare(other) < 0;
    }
    
    bool operator>(const Derived& other) const {
        return other < *static_cast<const Derived*>(this);
    }
    
    bool operator==(const Derived& other) const {
        return !(*static_cast<const Derived*>(this) < other) && 
               !(other < *static_cast<const Derived*>(this));
    }
};
class Person : public Printable<Person>, public Comparable<Person> {
public:
    Person(std::string n, int a) : name(n), age(a) {}
    
    std::string toString() const {
        return name + " (" + std::to_string(age) + ")";
    }
    
    int compare(const Person& other) const {
        return age - other.age;
    }
    
private:
    std::string name;
    int age;
};
int main() {
    Person p1("Alice", 30);
    Person p2("Bob", 25);
    
    p1.print();  // "Alice (30)"
    
    if (p1 > p2) {
        std::cout << "Alice is older\n";
    }
}

장점: Printable, Comparable독립적으로 조합할 수 있습니다.

5. 자주 발생하는 문제와 해결법

문제 1: 순환 의존성

증상: error: invalid use of incomplete type. 원인: BaseDerived를 사용할 때, Derived가 아직 정의되지 않았습니다.

// ❌ 잘못된 사용: Derived가 불완전
template<typename Derived>
class Base {
public:
    void func() {
        Derived d;  // Error: Derived 불완전
    }
};
// ✅ 올바른 사용: static_cast로 this 사용
template<typename Derived>
class Base {
public:
    void func() {
        static_cast<Derived*>(this)->implementation();
    }
};

문제 2: 가상 소멸자 누락

증상: 메모리 누수. 원인: CRTP는 다형성 삭제를 지원하지 않으므로, 가상 소멸자가 필요 없습니다. 오히려 금지해야 합니다.

// ❌ 잘못된 사용: 가상 소멸자
template<typename Derived>
class Base {
public:
    virtual ~Base() = default;  // 불필요
};
// ✅ 올바른 사용: 가상 소멸자 없음
template<typename Derived>
class Base {
public:
    ~Base() = default;
protected:
    ~Base() = default;  // 또는 protected로 다형성 삭제 방지
};

문제 3: 타입 안전성 부족

증상: 잘못된 파생 클래스 전달. 원인: 템플릿 인자를 잘못 전달해도 컴파일 에러가 나지 않을 수 있습니다.

// ❌ 잘못된 사용: 잘못된 타입 전달
class Wrong : public Base<AnotherClass> {};  // 의도와 다름
// ✅ 올바른 사용: static_assert로 검증
template<typename Derived>
class Base {
    static_assert(std::is_base_of_v<Base<Derived>, Derived>,
                  "Derived must inherit from Base<Derived>");
};

6. 프로덕션 패턴

패턴 1: 연산자 자동 생성

template<typename Derived>
class EqualityComparable {
public:
    friend bool operator==(const Derived& lhs, const Derived& rhs) {
        return lhs.equal(rhs);
    }
    
    friend bool operator!=(const Derived& lhs, const Derived& rhs) {
        return !(lhs == rhs);
    }
};
class Point : public EqualityComparable<Point> {
public:
    Point(int x, int y) : x_(x), y_(y) {}
    
    bool equal(const Point& other) const {
        return x_ == other.x_ && y_ == other.y_;
    }
    
private:
    int x_, y_;
};

패턴 2: 싱글톤

template<typename Derived>
class Singleton {
public:
    static Derived& instance() {
        static Derived inst;
        return inst;
    }
    
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    
protected:
    Singleton() = default;
};
class Logger : public Singleton<Logger> {
    friend class Singleton<Logger>;
public:
    void log(const std::string& msg) {
        std::cout << "[LOG] " << msg << '\n';
    }
private:
    Logger() = default;
};
int main() {
    Logger::instance().log("Hello");
}

패턴 3: 체이닝

template<typename Derived>
class Chainable {
protected:
    Derived& self() {
        return static_cast<Derived&>(*this);
    }
};
class Builder : public Chainable<Builder> {
public:
    Builder& setName(std::string n) {
        name = n;
        return self();
    }
    
    Builder& setAge(int a) {
        age = a;
        return self();
    }
    
    void build() {
        std::cout << name << ", " << age << '\n';
    }
    
private:
    std::string name;
    int age;
};
int main() {
    Builder()
        .setName("Alice")
        .setAge(30)
        .build();
}

7. 완전한 예제: 수학 연산자

#include <iostream>
#include <cmath>
template<typename Derived>
class Numeric {
public:
    Derived& operator+=(const Derived& rhs) {
        auto& self = static_cast<Derived&>(*this);
        self.add(rhs);
        return self;
    }
    
    Derived& operator-=(const Derived& rhs) {
        auto& self = static_cast<Derived&>(*this);
        self.subtract(rhs);
        return self;
    }
    
    friend Derived operator+(Derived lhs, const Derived& rhs) {
        lhs += rhs;
        return lhs;
    }
    
    friend Derived operator-(Derived lhs, const Derived& rhs) {
        lhs -= rhs;
        return lhs;
    }
};
class Vector2D : public Numeric<Vector2D> {
public:
    Vector2D(double x = 0, double y = 0) : x_(x), y_(y) {}
    
    void add(const Vector2D& other) {
        x_ += other.x_;
        y_ += other.y_;
    }
    
    void subtract(const Vector2D& other) {
        x_ -= other.x_;
        y_ -= other.y_;
    }
    
    double length() const {
        return std::sqrt(x_ * x_ + y_ * y_);
    }
    
    void print() const {
        std::cout << "(" << x_ << ", " << y_ << ")\n";
    }
    
private:
    double x_, y_;
};
int main() {
    Vector2D v1(3, 4);
    Vector2D v2(1, 2);
    
    Vector2D v3 = v1 + v2;
    v3.print();  // (4, 6)
    
    std::cout << "Length: " << v3.length() << '\n';  // 7.21110
}

8. 성능 비교

벤치마크: 가상 함수 vs CRTP

#include <chrono>
#include <iostream>
// 가상 함수
class VirtualBase {
public:
    virtual int compute(int x) const = 0;
    virtual ~VirtualBase() = default;
};
class VirtualDerived : public VirtualBase {
public:
    int compute(int x) const override {
        return x * x;
    }
};
// CRTP
template<typename Derived>
class CRTPBase {
public:
    int compute(int x) const {
        return static_cast<const Derived*>(this)->computeImpl(x);
    }
};
class CRTPDerived : public CRTPBase<CRTPDerived> {
public:
    int computeImpl(int x) const {
        return x * x;
    }
};
int main() {
    constexpr int N = 100'000'000;
    
    // 가상 함수
    VirtualDerived vd;
    VirtualBase* vptr = &vd;
    auto start = std::chrono::high_resolution_clock::now();
    int sum1 = 0;
    for (int i = 0; i < N; ++i) {
        sum1 += vptr->compute(i);
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto virtual_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
    // CRTP
    CRTPDerived cd;
    start = std::chrono::high_resolution_clock::now();
    int sum2 = 0;
    for (int i = 0; i < N; ++i) {
        sum2 += cd.compute(i);
    }
    end = std::chrono::high_resolution_clock::now();
    auto crtp_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
    std::cout << "Virtual: " << virtual_time << " ms\n";
    std::cout << "CRTP: " << crtp_time << " ms\n";
    std::cout << "Speedup: " << (double)virtual_time / crtp_time << "x\n";
}

결과 (예시):

Virtual: 450 ms
CRTP: 120 ms
Speedup: 3.75x

이유: CRTP는 인라인 최적화가 가능하고, vtable 조회가 없습니다.

정리

개념설명
CRTPCuriously Recurring Template Pattern
목적컴파일 타임 다형성, 가상 함수 오버헤드 제거
구조Base<Derived>, static_cast<Derived*>(this)
장점인라인 최적화, vtable 없음, 타입 안전
단점런타임 다형성 불가, 코드 중복 가능
사용 사례정적 카운터, Mixin, 연산자 자동 생성
CRTP는 성능이 중요한 라이브러리에서 가상 함수 오버헤드를 제거하는 강력한 패턴입니다.

FAQ

Q1: CRTP는 언제 쓰나요?

A: 성능이 중요하고, 컴파일 타임에 타입이 결정되며, 런타임 다형성이 필요 없을 때 사용합니다.

Q2: 가상 함수와 차이는?

A: 가상 함수는 런타임 다형성 (vtable 조회), CRTP는 컴파일 타임 다형성 (인라인 최적화).

Q3: 단점은?

A: 런타임 다형성 불가 (포인터로 다형성 삭제 불가), 코드 중복 (템플릿 인스턴스화).

Q4: Mixin과 차이는?

A: Mixin은 기능 조합, CRTP는 인터페이스 강제 + 정적 다형성. 함께 사용 가능합니다.

Q5: 가상 소멸자가 필요한가요?

A: 불필요합니다. CRTP는 다형성 삭제를 지원하지 않으므로, 오히려 protected 소멸자로 방지하는 것이 좋습니다.

Q6: CRTP 학습 리소스는?

A:

  • “Modern C++ Design” by Andrei Alexandrescu
  • “C++ Templates: The Complete Guide” by Vandevoorde & Josuttis
  • Fluent C++: CRTP 한 줄 요약: CRTP로 가상 함수 오버헤드 없이 컴파일 타임 다형성을 구현할 수 있습니다. 다음으로 Tag Dispatch를 읽어보면 좋습니다.

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, crtp, template, polymorphism, pattern, static 등으로 검색하시면 이 글이 도움이 됩니다.