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

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

이 글의 핵심

C++ 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. 기본 구조
  2. 인터페이스 강제
  3. 정적 카운터
  4. Mixin과 CRTP
  5. 자주 발생하는 문제와 해결법
  6. 프로덕션 패턴
  7. 완전한 예제: 수학 연산자
  8. 성능 비교

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++ 템플릿 | “제네릭 프로그래밍” 초보자 가이드
  • C++ 가상 함수 | “Virtual Functions” 가이드
  • C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축

관련 글

  • C++ CRTP 패턴 |
  • C++ Factory Pattern 완벽 가이드 | 객체 생성 캡슐화와 확장성
  • C++ Mixin |
  • C++ Strategy Pattern 완벽 가이드 | 알고리즘 캡슐화와 런타임 교체
  • C++ Visitor Pattern |