Home >Backend Development >C++ >Can Strongly Typed Enums Be Automatically Converted to Integers in C ?
Automating Strongly Typed Enum to Integer Conversion
In C , enums come in two flavors: strongly typed enums and regular enums. Regular enums can be implicitly converted to integers, while strongly typed enums require an explicit cast. This raises the question: is there an automated way to convert strongly typed enums to integers without resorting to explicit casts?
The answer is no, and it's intentional. Strongly typed enums are designed to prevent the implicit conversion to integers. Essentially, the compiler ensures that you explicitly acknowledge the conversion from an enumerated value to an integer.
However, there is a workaround to avoid specifying the underlying type in the cast. By utilizing a template function, we can abstract away the cast's type specification.
<code class="cpp">template <typename E> constexpr typename std::underlying_type<E>::type to_underlying(E e) noexcept { return static_cast<typename std::underlying_type<E>::type>(e); }</code>
With this template function, the conversion can be achieved as follows:
<code class="cpp">std::cout << foo(to_underlying(b::B2)) << std::endl;</code>
This approach eliminates the explicit type specification in the cast, simplifying the conversion process while maintaining the desired behavior of enforced explicit conversion for strongly typed enums.
The above is the detailed content of Can Strongly Typed Enums Be Automatically Converted to Integers in C ?. For more information, please follow other related articles on the PHP Chinese website!