C++ Type Erasure | Unified Interfaces Without Inheritance

C++ Type Erasure | Unified Interfaces Without Inheritance

이 글의 핵심

How type erasure works and when standard-library facilities already use it.

What is type erasure?

Type erasure hides concrete types behind a small, stable interface—often via a concept table + erased storage (std::function, std::any, custom Drawable wrappers).

graph TD
    A[Stable API] --> B[Concept interface]
    B --> C[Model for type A]
    B --> D[Model for type B]

std::function

Erases callable types with a given signature:

std::function<int(int,int)> f = [](int a, int b) { return a + b; };

std::any

Stores any copyable value; type must be recovered with any_cast and correct type.

Manual pattern

Drawable holding unique_ptr<DrawableConcept> + templated DrawableModel<T>—see the Korean article for a full sketch.

Tradeoffs

VirtualsType erasure
InheritanceRequiredNot required
Indirectionvtableoften heap + function pointers
FlexibilityLimited to hierarchyMany unrelated types

  • std::any
  • Polymorphism

Keywords

C++, type erasure, std::function, std::any, design patterns