More C++ Idioms/Type Erasure

= Type Erasure =

Intent
To provide a type-neutral container that interfaces a variety of concrete types.

Also Known As
"Variant" (not to be confused with ). This technique is used inside  and.

Motivation
It is often useful to have a variable which can contain more than one type. Type Erasure is a technique to represent a variety of concrete types through a single generic interface.

Implementation and Example
Type Erasure is achieved in C++ by encapsulating a concrete implementation in a generic wrapper and providing virtual accessor methods to the concrete implementation via a generic interface.

The key components in this example interface are var, inner_base and inner classes: The var class holds a pointer to the inner_base class. Concrete implementations on inner (such as inner or inner) inherit from inner_base. The var representation will access the concrete implementations through the generic inner_base interface. To hold arbitrary types of data a little more scaffolding is needed: The utility of an erased type is to assign multiple typed values to it so an assignment operator achieves just that: Creating an erased type and assigning it various values isn't of much use unless you can interrogate it. One useful method is to query for the underlying type info: Here the var class forwards calls of Type to it's inner_base interface which is overridden by the concrete inner<_Ty> subclass which ultimately returns the underlying type. This technique of forwarding accessor methods to a virtual interface which is overridden by concrete implementations is expanded for a fully useful generic type.