C++ Type Erasure | "타입 지우기" 패턴 가이드
이 글의 핵심
Type Erasure (타입 소거) 는 타입 정보를 숨기고 통일된 인터페이스로 다양한 타입을 처리하는 디자인 패턴입니다. 상속 없이도 다형성을 구현할 수 있으며, std::any, std::function 등이 이 패턴을 사용합니다.
Type Erasure란?
Type Erasure (타입 소거) 는 타입 정보를 숨기고 통일된 인터페이스로 다양한 타입을 처리하는 디자인 패턴입니다. 상속 없이도 다형성을 구현할 수 있으며, std::any, std::function 등이 이 패턴을 사용합니다.
#include <any>
#include <iostream>
using namespace std;
int main() {
any a = 10;
cout << any_cast<int>(a) << endl; // 10
a = 3.14;
cout << any_cast<double>(a) << endl; // 3.14
a = string("Hello");
cout << any_cast<string>(a) << endl; // Hello
}
왜 필요한가?:
- 상속 불필요: 기존 타입을 수정하지 않고 다형성 구현
- 유연성: 컴파일 타임에 타입을 알 수 없을 때
- 디커플링: 타입 간 의존성 제거
- 재사용성: 다양한 타입에 대해 동일한 인터페이스 제공
// ❌ 가상 함수: 상속 필요
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape { // 상속 필요
void draw() override {}
};
// ✅ Type Erasure: 상속 불필요
class Drawable {
// 내부 구현...
};
class Circle { // 상속 불필요!
void draw() {}
};
Drawable d = Circle(); // OK
d.draw();
Type Erasure의 구조:
graph TD
A[Drawable 외부 인터페이스] --> B[DrawableConcept 추상 인터페이스]
B --> C["DrawableModelCircle"]
B --> D["DrawableModelRectangle"]
C --> E[Circle 객체]
D --> F[Rectangle 객체]
style A fill:#90EE90
style B fill:#FFB6C1
style C fill:#87CEEB
style D fill:#87CEEB
Type Erasure vs 가상 함수:
| 특징 | 가상 함수 | Type Erasure |
|---|---|---|
| 상속 | ✅ 필요 | ❌ 불필요 |
| 기존 타입 수정 | ✅ 필요 | ❌ 불필요 |
| 유연성 | ❌ 제한적 | ✅ 높음 |
| 구현 복잡도 | ✅ 낮음 | ❌ 높음 |
| 성능 | ✅ 빠름 | ❌ 약간 느림 |
| 타입 정보 | ✅ 유지 | ❌ 소거 |
// 가상 함수: 상속 필요
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
void draw() override {
std::cout << "원\n";
}
};
// Type Erasure: 상속 불필요
class Circle { // Shape 상속 안함
public:
void draw() const {
std::cout << "원\n";
}
};
Drawable d = Circle(); // OK
std::function
#include <functional>
int add(int a, int b) { return a + b; }
int main() {
// 함수 포인터
function<int(int, int)> f1 = add;
// 람다
function<int(int, int)> f2 = { return a * b; };
// 함수 객체
struct Multiply {
int operator()(int a, int b) { return a * b; }
};
function<int(int, int)> f3 = Multiply();
cout << f1(2, 3) << endl; // 5
cout << f2(2, 3) << endl; // 6
cout << f3(2, 3) << endl; // 6
}
수동 Type Erasure 구현
class Drawable {
private:
struct DrawableConcept {
virtual void draw() const = 0;
virtual ~DrawableConcept() {}
};
template<typename T>
struct DrawableModel : DrawableConcept {
T object;
DrawableModel(T obj) : object(move(obj)) {}
void draw() const override {
object.draw();
}
};
unique_ptr<DrawableConcept> self;
public:
template<typename T>
Drawable(T obj) : self(make_unique<DrawableModel<T>>(move(obj))) {}
void draw() const {
self->draw();
}
};
class Circle {
public:
void draw() const {
cout << "원 그리기" << endl;
}
};
class Rectangle {
public:
void draw() const {
cout << "사각형 그리기" << endl;
}
};
int main() {
vector<Drawable> shapes;
shapes.push_back(Circle());
shapes.push_back(Rectangle());
for (const auto& shape : shapes) {
shape.draw();
}
}
실전 예시
예시 1: 콜백 시스템
#include <functional>
#include <vector>
class EventSystem {
private:
vector<function<void(int)>> handlers;
public:
template<typename Func>
void subscribe(Func&& handler) {
handlers.push_back(forward<Func>(handler));
}
void trigger(int value) {
for (auto& handler : handlers) {
handler(value);
}
}
};
void globalHandler(int x) {
cout << "전역 함수: " << x << endl;
}
int main() {
EventSystem events;
// 전역 함수
events.subscribe(globalHandler);
// 람다
events.subscribe( {
cout << "람다: " << x << endl;
});
// 함수 객체
struct Printer {
void operator()(int x) {
cout << "함수 객체: " << x << endl;
}
};
events.subscribe(Printer());
events.trigger(42);
}
예시 2: 타입 안전 any
class TypeSafeAny {
private:
struct Holder {
virtual ~Holder() {}
};
template<typename T>
struct HolderImpl : Holder {
T value;
HolderImpl(T v) : value(move(v)) {}
};
unique_ptr<Holder> content;
public:
template<typename T>
TypeSafeAny(T value) : content(make_unique<HolderImpl<T>>(move(value))) {}
template<typename T>
T* get() {
if (auto* holder = dynamic_cast<HolderImpl<T>*>(content.get())) {
return &holder->value;
}
return nullptr;
}
};
int main() {
TypeSafeAny a = 42;
if (int* p = a.get<int>()) {
cout << *p << endl; // 42
}
if (string* p = a.get<string>()) {
cout << *p << endl;
} else {
cout << "타입 불일치" << endl;
}
}
예시 3: 플러그인 시스템
class Plugin {
private:
struct PluginConcept {
virtual void execute() = 0;
virtual string getName() = 0;
virtual ~PluginConcept() {}
};
template<typename T>
struct PluginModel : PluginConcept {
T plugin;
PluginModel(T p) : plugin(move(p)) {}
void execute() override {
plugin.execute();
}
string getName() override {
return plugin.getName();
}
};
unique_ptr<PluginConcept> self;
public:
template<typename T>
Plugin(T plugin) : self(make_unique<PluginModel<T>>(move(plugin))) {}
void execute() {
self->execute();
}
string getName() {
return self->getName();
}
};
class AudioPlugin {
public:
void execute() {
cout << "오디오 처리" << endl;
}
string getName() {
return "AudioPlugin";
}
};
class VideoPlugin {
public:
void execute() {
cout << "비디오 처리" << endl;
}
string getName() {
return "VideoPlugin";
}
};
int main() {
vector<Plugin> plugins;
plugins.push_back(AudioPlugin());
plugins.push_back(VideoPlugin());
for (auto& plugin : plugins) {
cout << plugin.getName() << ": ";
plugin.execute();
}
}
std::any 활용
#include <any>
#include <map>
class PropertyBag {
private:
map<string, any> properties;
public:
template<typename T>
void set(const string& key, T value) {
properties[key] = value;
}
template<typename T>
T get(const string& key) {
return any_cast<T>(properties[key]);
}
bool has(const string& key) {
return properties.find(key) != properties.end();
}
};
int main() {
PropertyBag props;
props.set("width", 800);
props.set("height", 600);
props.set("title", string("My App"));
cout << props.get<int>("width") << endl;
cout << props.get<string>("title") << endl;
}
자주 발생하는 문제
문제 1: any_cast 실패
// ❌ 크래시
any a = 42;
string s = any_cast<string>(a); // bad_any_cast 예외
// ✅ 안전한 캐스트
if (a.type() == typeid(int)) {
int x = any_cast<int>(a);
}
// ✅ 포인터 캐스트
if (int* p = any_cast<int>(&a)) {
cout << *p << endl;
}
문제 2: function 복사 비용
// ❌ 큰 람다 캡처
vector<int> bigData(1000000);
function<void()> f = [bigData]() { // 복사!
// ...
};
// ✅ 참조 캡처
function<void()> f = [&bigData]() {
// ...
};
문제 3: 타입 정보 손실
// ❌ 타입 정보 손실
any a = Circle();
// Circle의 메서드를 직접 호출 불가
// ✅ Type Erasure 패턴으로 인터페이스 제공
Drawable d = Circle();
d.draw(); // OK
Type Erasure vs 가상 함수
// 가상 함수
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
void draw() override {}
};
// Type Erasure
class Drawable {
// 내부 구현...
};
class Circle { // 상속 불필요!
void draw() {}
};
장점:
- 상속 불필요
- 기존 타입 수정 불필요
- 더 유연함
단점:
- 구현 복잡
- 약간의 오버헤드
실무 패턴
패턴 1: 타입 안전 메시지 큐
class Message {
private:
struct MessageConcept {
virtual void process() = 0;
virtual ~MessageConcept() {}
};
template<typename T>
struct MessageModel : MessageConcept {
T message;
MessageModel(T msg) : message(std::move(msg)) {}
void process() override {
message.process();
}
};
std::unique_ptr<MessageConcept> self_;
public:
template<typename T>
Message(T msg) : self_(std::make_unique<MessageModel<T>>(std::move(msg))) {}
void process() {
self_->process();
}
};
// 사용
struct TextMessage {
std::string content;
void process() const {
std::cout << "텍스트: " << content << '\n';
}
};
struct ImageMessage {
std::vector<uint8_t> data;
void process() const {
std::cout << "이미지: " << data.size() << " bytes\n";
}
};
std::queue<Message> queue;
queue.push(TextMessage{"Hello"});
queue.push(ImageMessage{{1, 2, 3}});
패턴 2: 커맨드 패턴
class Command {
private:
struct CommandConcept {
virtual void execute() = 0;
virtual void undo() = 0;
virtual ~CommandConcept() {}
};
template<typename T>
struct CommandModel : CommandConcept {
T command;
CommandModel(T cmd) : command(std::move(cmd)) {}
void execute() override {
command.execute();
}
void undo() override {
command.undo();
}
};
std::unique_ptr<CommandConcept> self_;
public:
template<typename T>
Command(T cmd) : self_(std::make_unique<CommandModel<T>>(std::move(cmd))) {}
void execute() { self_->execute(); }
void undo() { self_->undo(); }
};
// 사용
struct AddCommand {
int& value;
int delta;
void execute() { value += delta; }
void undo() { value -= delta; }
};
int value = 0;
std::vector<Command> history;
history.push_back(AddCommand{value, 10});
history.back().execute(); // value = 10
history.back().undo(); // value = 0
패턴 3: 함수 래퍼
template<typename Signature>
class Function;
template<typename R, typename... Args>
class Function<R(Args...)> {
private:
struct Callable {
virtual R call(Args... args) = 0;
virtual ~Callable() {}
};
template<typename F>
struct CallableImpl : Callable {
F func;
CallableImpl(F f) : func(std::move(f)) {}
R call(Args... args) override {
return func(std::forward<Args>(args)...);
}
};
std::unique_ptr<Callable> callable_;
public:
template<typename F>
Function(F func) : callable_(std::make_unique<CallableImpl<F>>(std::move(func))) {}
R operator()(Args... args) {
return callable_->call(std::forward<Args>(args)...);
}
};
// 사용
Function<int(int, int)> add = { return a + b; };
std::cout << add(2, 3) << '\n'; // 5
FAQ
Q1: Type Erasure는 언제 사용하나요?
A:
- 상속 없이 다형성: 기존 타입을 수정할 수 없을 때
- 유연한 인터페이스: 다양한 타입을 통일된 방식으로 처리
- 플러그인 시스템: 런타임에 타입이 결정될 때
- 콜백 시스템: 다양한 callable 객체 저장
// 상속 없이 다형성
class Circle { // Shape 상속 안함
void draw() const {}
};
Drawable d = Circle(); // OK
Q2: any vs variant?
A:
- any: 어떤 타입이든 가능 (런타임 체크, 느림)
- variant: 정해진 타입 중 하나 (컴파일 타임 체크, 빠름)
// any: 모든 타입
std::any a = 42;
a = std::string{"hello"};
a = std::vector<int>{1, 2, 3};
// variant: 정해진 타입만
std::variant<int, std::string> v = 42;
v = std::string{"hello"};
// v = std::vector<int>{}; // 에러
Q3: function의 오버헤드는?
A: 약간의 오버헤드가 있습니다. 가상 함수 호출과 유사합니다.
// 직접 호출: ~1ns
int add(int a, int b) { return a + b; }
add(2, 3);
// std::function: ~5-10ns
std::function<int(int, int)> f = add;
f(2, 3);
권장: 성능이 중요하면 템플릿 사용
Q4: Type Erasure 구현은 어렵나요?
A: 복잡합니다. 가능하면 std::any, std::function을 사용하세요.
// ✅ std::function 사용 (간단)
std::function<void()> callback = {
std::cout << "Hello\n";
};
// ❌ 직접 구현 (복잡)
// Concept, Model, 외부 인터페이스 필요
Q5: 성능이 중요하면?
A: 가상 함수나 CRTP를 고려하세요.
// 가상 함수: 빠름, 상속 필요
class Shape {
virtual void draw() = 0;
};
// CRTP: 매우 빠름, 복잡
template<typename Derived>
class Shape {
void draw() {
static_cast<Derived*>(this)->draw_impl();
}
};
// Type Erasure: 유연함, 약간 느림
class Drawable {
// ...
};
Q6: Type Erasure의 메모리 할당은?
A: 동적 할당이 필요합니다. 작은 객체는 Small Object Optimization (SOO)을 사용할 수 있습니다.
// 동적 할당
Drawable d = Circle(); // new로 할당
// std::function: SOO 사용
std::function<void()> f = {}; // 작은 람다: 스택
std::function<void()> f2 = [bigData]() {}; // 큰 람다: 힙
Q7: Type Erasure는 복사 가능한가요?
A: 구현에 따라 다릅니다. 복사를 지원하려면 clone() 메서드가 필요합니다.
struct DrawableConcept {
virtual void draw() const = 0;
virtual std::unique_ptr<DrawableConcept> clone() const = 0; // 복사
virtual ~DrawableConcept() {}
};
template<typename T>
struct DrawableModel : DrawableConcept {
T object;
std::unique_ptr<DrawableConcept> clone() const override {
return std::make_unique<DrawableModel>(object);
}
};
Q8: Type Erasure 학습 리소스는?
A:
- “C++ Software Design” by Klaus Iglberger
- Sean Parent의 “Inheritance Is The Base Class of Evil” 발표
- Boost.TypeErasure 라이브러리
관련 글: any, variant, function, virtual-functions.
한 줄 요약: Type Erasure는 타입 정보를 숨기고 상속 없이 다형성을 구현하는 디자인 패턴입니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ any | “타입 소거” 가이드
- C++ 기본 인자 | “Default Arguments” 가이드
- C++ Return Statement | “반환문” 가이드
관련 글
- C++ any |
- C++ std::function vs 함수 포인터 |
- C++ std::any vs void* |
- C++ CRTP 패턴 |
- C++ 기본 인자 |