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.
template
constexpr typename std::underlying_type::type to_underlying(E e) noexcept {
return static_cast::type>(e);
}
With this template function, the conversion can be achieved as follows:
std::cout 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3