Site Tools


wiki:cpp-type-erasure

Table of Contents

C++ Type erasure

Type erasure is a technique that allows storing and manipulating objects of different types through a common interface, typically using virtual functions or std::any. This hides the specific type from the container, trading compile-time type safety for runtime flexibility.

Use type erasure sparingly: prefer templates for compile-time type safety; use type erasure only when runtime polymorphism across unrelated types is necessary.

Example

This example shows type erasure using virtual functions to handle different types uniformly.

// compile: g++ -o erase_type erase_type.cpp
// run: ./erase_type
// description: type erasure via virtual interface for runtime polymorphism
 
#include <iostream>
#include <vector>
#include <memory>
 
class Printer {
public:
    virtual ~Printer() = default;
    virtual void print() = 0;
};
 
template <typename T>
class TypedPrinter : public Printer {
private:
    T value;
public:
    TypedPrinter(const T& v) : value(v) {}
    void print() override {
        std::cout << "Value: " << value << "\n";
    }
};
 
int main() {
    std::vector<std::unique_ptr<Printer>> printers;
 
    printers.push_back(std::make_unique<TypedPrinter<int>>(42));
    printers.push_back(std::make_unique<TypedPrinter<double>>(3.14));
    printers.push_back(std::make_unique<TypedPrinter<std::string>>(std::string("hello")));
 
    for (auto& p : printers) {
        p->print();
    }
 
    return 0;
}
wiki/cpp-type-erasure.md · Last modified: by 127.0.0.1