Implementing type-erasure in C++ for polymorphic interfaces
This is a hard C++ coding problem that tests your understanding of type-erasure—a technique for wrapping objects of different concrete types behind a single non-template interface. Rather than using virtual inheritance, type-erasure decouples the wrapper from the concrete types it consumes, making it possible to store and call methods on heterogeneous objects uniformly.
The problem asks you to build a type-erased wrapper that accepts any class with an attack method, without modifying the wrapper's inheritance hierarchy or converting it to a template. This requires careful use of internal template helpers, type-safe storage, and function pointers or callable wrappers to delegate calls to the underlying object. Strong solutions handle deep copies, lifetime management, and ensure that the wrapper is both memory-efficient and thread-safe when the underlying objects are.
- Virtual function tables and pointer indirection
- Template specialization and friend declarations
- Move semantics and copy construction for non-owning vs. owning wrappers
- Memory layout and alignment considerations for small-object optimization