Type destroyer is type restorer

Problem You need to take some typed data and pack it into a format that contains no type information (e.g., char array, or cast pointer type to void*). How do you extract this data later in a type safe way?

Context The typeless data is a construct for program convenience. The typeless data will not be made persistent or otherwise be transferred across process boundaries.

Forces To maximize the flexibility of some code, it is useful to use void pointers or copy chunks of data into char arrays. There is no type-safe way in C++ to cast void pointers or data that was stored in a char array. C++ allows the cast, but does not guarantee that it is safe.

Solution Create a single object that will both write to and read from the typeless data. When storing data, this object will be the last to see the actual type of the data. When restoring the data, the object that was the last to see the data type information will be the object that casts the typeless data to having the correct type again. Often this object will be templated by the actual type of the data to create a general type destroyer and restorer.

Forces resolved Flexibility is achieved by being able to change data into very generic types. Type safety is guaranteed because only an object that knows without a doubt what the type of the actual data is will cast the generic form to that type.

Design rationale There are times, such as when aggressively factoring a template, when it is handy to write a class in terms of void pointers, or create a class that can store information in a fixed size array. Another object, usually a template, can provide a type safe veneer over the generically typed object. The type safe layer converts to and from the generic types. Only the type safe layer can access the generically typed layer so it knows exactly what is stored in the generic layer and can perform the casts without worrying.

[Source: Paul Jakubik, "Comparing object ownership alternatives", C++ Report, Oct 97, p49]