More C++ Idioms/Boost mutant

= Boost mutant =

Intent
Reorder the data members of a plain old data (POD) type when all members are of the same type, without physically reorganizing or copying the data items.

Motivation
The need of this idiom is best motivated using Boost's Bimap. Boost.Bimap is a bidirectional maps library for C++. In, values of types X and Y can both serve as keys. The implementation of such a data structure can be optimized using the boost mutant idiom.

Solution and Sample Code
Boost mutant idiom makes use of reinterpret_cast and depends heavily on the assumption that the memory layouts of two different structures with identical data members (types and order) are interchangeable. Although the C++ standard does not guarantee this property, virtually all the compilers satisfy it. Moreover, the mutant idiom is standard if only POD types are used. The following example shows how the boost mutant idiom works.

Given a  object of POD data members only, the layout of the   is identical to that of pair's on most compilers. The  template reverses the names of the data members without physically reversing the data. A helper  function is used to easily construct a   reference, which can be considered as a view over the original pair object. The output of the above program confirms that the reverse view can be obtained without reorganizing data:

p.first = 1.34, p.second = 5 mutate(p).first = 5, mutate(p).second = 1.34

Known Uses

 * Boost.Bimap