# C++ Type erasure **[Type erasure](https://en.cppreference.com/w/cpp/any)** 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. ```cpp // compile: g++ -o erase_type erase_type.cpp // run: ./erase_type // description: type erasure via virtual interface for runtime polymorphism #include #include #include class Printer { public: virtual ~Printer() = default; virtual void print() = 0; }; template 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> printers; printers.push_back(std::make_unique>(42)); printers.push_back(std::make_unique>(3.14)); printers.push_back(std::make_unique>(std::string("hello"))); for (auto& p : printers) { p->print(); } return 0; } ```