cpp / expert
Snippet
Type Erasure Pattern for Polymorphic Value Semantics
The Type Erasure pattern combines templated constructors with internal inheritance (Concept and Model) to provide duck-typed value semantics without exposing template arguments in the class interface. This offers non-intrusive runtime polymorphism for unrelated types sharing an implicit interface, avoiding inheritance hierarchies on user-defined types.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>#include <memory>#include <string>class Printable {public:template <typename T>Printable(T val) : concept_(std::make_unique<Model<T>>(std::move(val))) {}void print() const { concept_->print_impl(); }private:struct Concept {virtual ~Concept() = default;virtual void print_impl() const = 0;};template <typename T>struct Model final : Concept {Model(T val) : value_(std::move(val)) {}void print_impl() const override { std::cout << value_ << '\n'; }T value_;};std::unique_ptr<Concept> concept_;};int main() {Printable p1(100);Printable p2(std::string("Type Erasure in Action"));p1.print();p2.print();}
Breakdown
1
template <typename T> Printable(T val)
Template constructor accepts any type supporting the required printing operations.
2
struct Concept
Private abstract interface defining the internal polymorphic contract.
3
template <typename T> struct Model final : Concept
Templated concrete derived class wrapping the underlying payload type.