



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




I’ve used type erasure in C++ for years without giving it much thought. For example, std::function is a well-known polymorphic, type erased template class that holds a callable object—any function, lambda, or functor. The concrete type of the callable is "erased"; it’s hidden from the user (I know this sounds weird, but it will make sense later). What remains is a uniform interface to invoke it. The classes std::any and std::shared_ptr are other good examples of type erasure. In their book C++ Template Meta-programming: Concepts, Tools, and Techniques from Boost and Beyond , Dave Abrahams and Aleksey Gurtovoy define type erasure as “the process of turning a wide variety of types with a common interface into one type with that same interface.” This is an apt description. The excellent book Software Design in C++ by Klaus Iglberger provided me with a solid foundation in the mechanics of type erasure. Chapter 7 lays the groundwork, and Chapter 8 dives into type erasure in detail, including several performance optimizations. I leave it to the reader to obtain the book and do some studying; there is a lot of valuable learning there about design patterns and modern C++ in addition to type erasure. In practice, type erasure is implemented as a combination of several different design patterns; according to Software Design in C++: External Polymorphism, Bridge, and optionally Prototype. I will not go into the details of these patterns here, but will point them out in the code that is presented in this chapter. Here is a quick refresher on the three patterns:
independently. The abstraction maintains a reference to the implementation and delegates work to it.
Type erasure is a powerful tool, but not always appropriate to a particular purpose. Don’t use type erasure when:
This is the defining characteristic of external polymorphism. The polymorphic behavior is moved out of the concrete types and into a separate abstraction layer. The result is a clean separation of concerns. Concrete measurement types model data and validation logic. The type-erased wrapper models uniform handling and ownership.
In this version of the design, concrete measurement types are adapted to the erased interface by wrapping them in a type-specific model class. For each concrete measurement type T, the wrapper instantiates a corresponding Model that implements the erased interface ( IMeasurementModel ) by delegating operations to the stored value. This adaptation does not require inheritance, traits, or helper templates. Concrete measurement types remain plain data structures with no knowledge that type erasure is being used. The adaptation occurs at runtime through virtual dispatch. If a concrete type does not support the operations required by the model, such as being printable for debugging, the error surfaces naturally at compile time when the model is instantiated. This approach keeps the design intentionally simple. More sophisticated compile- time adaptation techniques are possible and will be explored later, but they are deliberately avoided here to keep the mechanics of type erasure easy to understand.
Adding a new measurement type does not require modifying AnyMeasurement. As long as the new type provides the required operations, it automatically satisfies the erased concept. There are no base classes to inherit from. There are no virtual functions in the measurement types. There is no registration step. Concrete measurement types remain as plain data structures and the abstraction scales naturally as the system grows. This design provides a concrete example of the Open-Closed Principle (OCP). AnyMeasurement is closed for modification. Adding new measurement types requires no changes to its implementation. The design is open for extension because new measurement types are introduced by addition; no existing code is touched.
With the type-erased wrapper in place, using heterogeneous measurement types becomes straightforward. Different concrete measurement structures can be stored in the same container and passed through the same interfaces without exposing their concrete types. For example, a collection of system measurements can be represented as a simple sequence: std::vector measurements; Each element in the container may hold a different concrete measurement type, but consumers interact with them uniformly. Code that processes measurements no longer needs to know how they are represented internally. It depends only on the small, stable interface exposed by the type-erased wrapper. This is the primary benefit of the design. It allows measurement handling logic to be written once, in terms of concepts, rather than repeatedly rewritten for each concrete type.
int main() { MeasurementHeader tempHeader; tempHeader.name = "outdoor_temp"; tempHeader.units = "C"; tempHeader.timestampUs = 1736539200000000ULL; // demo number tempHeader.type = MeasurementType::Temperature; tempHeader.quality = Quality::Good; MeasurementHeader pressureHeader; pressureHeader.name = "baro_pressure"; pressureHeader.units = "kPa"; pressureHeader.timestampUs = 1736539200100000ULL; pressureHeader.type = MeasurementType::Pressure; pressureHeader.quality = Quality::Good; MeasurementHeader posHeader; posHeader.name = "gps_fix"; posHeader.units = "deg"; posHeader.timestampUs = 1736539200123456ULL; posHeader.type = MeasurementType::Position; posHeader.quality = Quality::Suspect;
This MVP is correct and easy to understand, but it is not adequate for an embedded target with strict memory constraints. This implementation uses heap allocation and virtual dispatch internally. In later chapters, we will revisit this design with explicit memory strategies that avoid per-object heap allocation and allow tighter control over latency and footprint.
In this chapter, we introduced type erasure as a practical design technique for representing heterogeneous system measurement types uniformly. We built a minimal, value-semantics wrapper that avoids inheritance, keeps concrete measurement types simple, and scales cleanly as new measurement types are added. The result is a small but powerful abstraction. It demonstrates external polymorphism in practice, enforces the Open–Closed Principle structurally, and provides a stable foundation for the more complex system behaviors that follow.