Embedded Template Library  1.0
 All Classes Files Functions Variables Typedefs Friends Modules Pages

Smart enumerations.
A method of declaring enumerations that allow grouping within a structure. Avoids the problem of clashing names that can occur with standard enumerations. One way to think of the code is as a type with built-in constants and an optional conversion to a string.

Declaring the enumeration.

struct CompassDirection
{
enum enum_type
{
North = 0,
South = 180,
East = 90,
West = 270
};
DECLARE_ENUM_TYPE(CompassDirection, int)
ENUM_TYPE(North, "North")
ENUM_TYPE(South, "South")
ENUM_TYPE(East, "East")
ENUM_TYPE(West, "West")
END_ENUM_TYPE
};

Using the enumeration.

CompassDirection direction; // Default construction.
direction = CompassDirection::North; // Assignment from an enumeration constant;
int value = direction; // Implicit conversion to 'int'.
direction = CompassDirection(value); // Explicit conversion from 'int'.
direction = CompassDirection(3); // Explicit conversion from an invalid value. This unfortunately cannot be avoided. Caveat emptor!
direction = value; // **** Compilation error ****
std::cout << "Direction = " << direction.to_string(); // Prints "Direction = North"

If a conversion to a string is not required then the 'ENUM_TYPE' declaration may be omitted. In that case the to_string() function will return a "?". This will also be the case for any enumeration value that does not have an ENUM_TYPE entry.