2013-04-30

C++11's strongly-typed enums

C++11 provides strongly-typed enums. These new enums are no longer simple sets of integers; they are classes in their own right. And, their instances are objects, too!

In the following example, we define several enumerated values for possible stereo configurations of a chemical bond.

enum class BondStereo : int8_t
{
NONE
, UP //!< Bond points up from the plane.
, DOWN //!< Bond points into the plane.
, UP_OR_DOWN //!< Bond may point up from or into the plane.
, E //!< Bond may be single or double, and has entgegen configuration.
, Z //!< Bond may be single or double, and has zusammen configuration.
, CIS //!< Double bond having cis configuration.
, TRANS //!< Double bond having trans configuration.
, UNSPECIFIED //!< Bond has unknown stereo geometry.
};

Note that the above enum class BondStereo has int8_t as its underlying data type. C++11 allows you to specify the precise integral data type that should be used. In turn, that allows us to choose specific types to best suit the required ranges of the enumerated values.

However, with this felicity comes an inconvenience. Since the instances of these enums are no longer simple integers, they cannot be used as such! The following is a simple and generic way of obtaining the underlying integral value of a given instance.