C++ 3.0 : Unscoped Enum:
// unscoped enum:
enum [identifier] [: type]
{enum-list};
Example: //NonScoped enum :
namespace NonScoped
{
enum Enum { num1, num2, num3, num4 };
void EnumFunction(Enum n_enum)
{
if (n_enum == num1)
{ /*...*/
}
}
}
Casting Rules :
1. In Unscoped enum an int is never implicitly convertible to an enum value.
int account_num = 135692;
Enum hand;
hand = account_num; // error C2440: '=' : cannot convert from 'int' to 'Enum'
2. A cast is required to convert an int to a scoped or unscoped enumerator.
hand = static_cast
3. You can promote a unscoped enumerator to an integer value without a cast.
int account_num = num3; //OK if num3 is in a unscoped enum
Using implicit conversions in this way can lead to unintended side-effects. To help eliminate programming errors associated with unscoped enums, scoped enum values are strongly typed.
C++ 11 : Scoped Enum / ENUM Class :
// scoped enum:
enum [class|struct]
[identifier] [: type]
{enum-list};
Example: // scoped enum:
namespace Scoped
{
enum class classEnaum { num1, num2, num3, num4 };
void enumFunction(classEnum c_enum)
{
if (c_enum == classEnum::num2)
{ /*...*/}
}
}
Casting Rules :
1. In scoped enum an int is never implicitly convertible to an enum value.
classEnaum hand;
hand = num2;
int account_num = 135692;
hand = account_num; // error C2440: '=' : cannot convert from 'int' to 'hand'
2. A cast is required to convert an int to a scoped or unscoped enumerator.
hand = static_cast
3. Scoped enumerators must be qualified by the enum type name (identifier) and cannot be implicitly converted
account_num = classEnaum::num2; // error C2440: '=' : cannot convert from 'Suit' to 'int'
account_num = static_cast
Advantages:
1. Cannot be implicitly converted (strongly typed)
2. Enum classes have another advantages over old-style enums. You can have a forward declaration to a strongly typed enum, meaning that you can write code like:
enum class Mood;
void assessMood (Mood m);
// later on:
enum class Mood { EXCITED, MOODY, BLUE };
Why forward declaration would this be useful? A forward declaration allows you to declare an enum type in the header file while putting specific values into the cpp file. This lets you change the list of possible enum values quite frequently without forcing all dependent files to recompile.
Comments
Post a Comment