All Notes

Type Erasure in C++

Last updated

Jul 28, 2025

Ideas from C++ SW Design (Klaus Iglberger) and cpp cons I want to write about it - but not sure i can explain as well as Klaus’ book/cpp cons yet Idea still budding…

Ideas from book

  • Small Buffer Optimization (SBO): Store small objects inline to avoid heap allocation
  • Move semantics: Implement move constructor/assignment for performance
  • Value semantics vs Reference semantics: Decide if container owns or references objects
  • Virtual function overhead: Each call goes through vtable—consider for hot paths
  • Memory allocation: Heap allocation per object unless using SBO
  • Exception safety: Ensure strong exception guarantee during copy/assignment
  • RTTI trade-off: Type erasure avoids templates but adds runtime indirection

Example from Klaus’ book


class Drawable {
struct Concept {
virtual ~Concept() = default;
virtual void draw() const = 0;
virtual Concept* clone() const = 0;
};

template<typename T>
struct Model : Concept {
T obj;
Model(T o) : obj(std::move(o)) {}
void draw() const override { obj.draw(); }
Concept* clone() const override { return new Model(*this); }
};

Concept* ptr;

public:
template<typename T>
Drawable(T obj) : ptr(new Model<T>(std::move(obj))) {}

~Drawable() { delete ptr; }
Drawable(const Drawable& d) : ptr(d.ptr->clone()) {}
Drawable& operator=(Drawable d) { std::swap(ptr, d.ptr); return *this; }

void draw() const { ptr->draw(); }
};

// Usage
struct Circle { void draw() const { /* ... */ } };
struct Square { void draw() const { /* ... */ } };

std::vector<Drawable> shapes;
shapes.push_back(Circle{});
shapes.push_back(Square{});
for (auto& s : shapes) s.draw();

Other notes about Software Design and/or C++