More C++ Idioms/Traits

= Traits =

Intent
To be able to use a common interface to get information about a type, even when the type cannot be changed to conform to any common interface.

Motivation
A function template might need to behave differently for different types based on information about those types. If only user-defined types can have members and member types that encode information about the enclosing type, then there will need to be a lot of special cases for builtin types like integers and pointers. By using a separate traits class with a primary specialization for types that can be modified to include certain members and specializations for types that cannot, functions can still use a common interface by using the traits class.

Solution and Sample Code
All traits classes have zero size and only include static members or subtypes. The primary specialization usually gets the values or types from members of the class whose traits are gotten. (In the below example, the member types come from base classes.) The specializations get the values or types from other means in such a way that the interface remains consistent. The cool thing about traits is that they are non-intrusive. This allows them to be applied to built-in types, like the specialization of  for arrays below. This also allows retroactive modeling.

Related Idioms

 * Type Generator