C++ enum class Usage Guide
In C++, the enum class is a strongly-typed enumeration that offers more rigorous type checking and improved scope control to prevent common errors.
The usage of an enum class is as follows:
enum class EnumName {
Value1,
Value2,
Value3
};
You can use an enum class in the following way:
EnumName variable = EnumName::Value1;
In this case, EnumName is the name of the enumeration type, and Value1, Value2, Value3 are the values of the enumeration. When using an enum class, you need to specify the values of the enumeration using the scope resolution operator (::).
Compared to traditional enumerations, enum class offers the following advantages:
- Type safety: Enum class’s enumeration values will not be implicitly converted to integer types, requiring explicit type conversion.
- Scope control: enum class ensures that the enumeration values are unique within the enum type and do not conflict with identifiers in other scopes.
- It is possible to explicitly specify the underlying type of an enumeration: by specifying the underlying type as int, char, etc., you can control how the enumeration values are stored.
It is important to note that when using enum class, enum values cannot be directly compared or operated with integers. You need to use static_cast or explicit type conversion of the enum class.