Type Erasure in C++
One Box, Any Type: Understanding Type Erasure in C++ Or: How std::function stores a lambda, a function pointer, and a functor in the same box C++ rewards precise thinking about types. Most of the time, that precision is a feature. But occasionally the type system and the design pull in opposite directions, and the compiler rejects code that is, by every conceptual measure, reasonable. Consider a transaction monitor for a SystemC simulation. Every time a TLM transaction arrives, four separate objects need to respond: a Logger records it, a LatencyTracker measures it, a ProtocolChecker validates it, a CoverageCollector bins it. They share no base class, and they shouldn't need one. What they have in common is purely behavioral: they all respond to a transaction. So the obvious thing gets written: std :: vector < TransactionHandler > handlers ; handlers . push_back ( Logger {}); handlers . push_back ( LatencyTracker {}); handlers . push_back ( Pr...