template<typename base>
class pearl::ScopedEnum< base >
The ScopedEnum class template can be used to define enumeration types which behave similar to C++11 scoped enums. That is, enumerators are contained within the scope of the enumeration type and can only be accessed using the scope resolution operator. Moreover, no implicit conversions to/from integral types are performed, which also prevents comparing values from different enumeration types. However, since this class template uses only pre-C++11 language features, some limitations exist. See the Limitations section below for details.
The ScopedEnum class template employs parameterized inheritance to derive the enumerators from a regular (unscoped) enum named type defined in a helper struct provided as the template parameter base. For example, to define a scoped enumeration type Color
with the three enumerators RED
, GREEN
and BLUE
, the following code snippet can be used:
struct Color_enum
{
enum type
{
RED,
GREEN,
BLUE
};
};
typedef ScopedEnum<Color_enum> Color;
The newly defined enumeration type Color
can then be used much like a C++11 scoped enum, except for some situations which are described in more detail below.
- Limitations
- Scoped enums cannot be fully emulated using pre-C++11 language features. That is, there are a few limitations that have to be considered when using enumeration types defined using this class template:
- The defined type is not a C++ enum. That is, its use may prevent certain compiler optimizations and therefore incur a performance penalty.
- The emulated scoped enum can not be directly used in
switch
statements. Instead, use the native_value() helper function:
- Likewise, direct casting to an integral type such as
int
is not possible. Again, use the native_value() helper function instead.
- The emulated scoped enum can not be directly used as a template parameter.
- Note
- To convert code using emulated scoped enums based on this class template to C++11, the following actions need to be performed:
- Adjust the enum type definition to use
enum class
instead of the helper struct and the typedef
.
- Find all uses of the native_value() helper function and either remove the function call (in
switch
statements) or replace it by a static_cast
to the corresponding integral type (for explicit type conversions).