In C++, strongly typed enumerations (also known as enum classes or enum class) provide enhanced type safety by preventing implicit type conversions. However, there are scenarios where you may need to convert such enumerations to an integer type, such as int. This conversion is not automatic and requires explicit handling.
Method 1: Using static_cast
The most straightforward approach is to use static_cast for type conversion, as illustrated below:
cpp#include <iostream> enum class Color : int { Red, Green, Blue }; int main() { Color color = Color::Green; // Explicit conversion of enumeration to int int colorValue = static_cast<int>(color); std::cout << "The color value is: " << colorValue << std::endl; return 0; }
In this example, the Color enumeration is a strongly typed enumeration defined based on int. When converting the color variable to int, we use static_cast<int>(color), which retrieves the integer value corresponding to the Green member (which starts from 0 by default, so Green corresponds to 1).
Method 2: Defining a Conversion Function
For frequent conversions, consider defining a conversion function within the class or using a helper function to improve code clarity and maintainability.
cpp#include <iostream> enum class Color : int { Red, Green, Blue }; // Helper function for converting enumeration to int int EnumToInt(Color color) { return static_cast<int>(color); } int main() { Color color = Color::Blue; int colorValue = EnumToInt(color); std::cout << "The color value is: " << colorValue << std::endl; return 0; }
Here, we define a EnumToInt function that accepts a Color parameter and returns the corresponding integer value. This allows you to call the function whenever conversion is needed, avoiding repeated use of static_cast in the code.
Conclusion
While strongly typed enumerations offer robust type safety, explicit type conversions (such as static_cast) or dedicated conversion functions enable convenient conversion of enumeration values to integers. The choice depends on the specific application context and code maintenance requirements.