Implicit Conversion of Strongly Typed Enums to Int
Strongly typed enums, introduced in C 11, are designed to prevent implicit conversions to integers. However, there may be cases where you want to convert a strongly typed enum value to an int without an explicit cast.
To address this, several approaches have been suggested:
You can define a function that performs the conversion. For instance:
<code class="cpp">#include <iostream> struct a { enum LOCAL_A { A1, A2 }; }; template <typename E> int to_int(E e) { return static_cast<int>(e); } int main() { // Use the to_int function to convert the strongly typed enum value b::B2 to int std::cout << to_int(b::B2) << std::endl; }</code>
To simplify the syntax, you can use a function template that automatically deduces the enum type:
<code class="cpp">#include <iostream> struct a { enum LOCAL_A { A1, A2 }; }; template <typename E> constexpr typename std::underlying_type<E>::type get_underlying(E e) noexcept { return static_cast<typename std::underlying_type<E>::type>(e); } int main() { // Use the get_underlying function to convert the strongly typed enum value b::B2 to int std::cout << get_underlying(b::B2) << std::endl; }</code>
You can also utilize a macro to make the conversion process more concise:
<code class="cpp">#include <iostream> struct a { enum LOCAL_A { A1, A2 }; }; #define TO_INT(e) static_cast<int>(e) int main() { // Use the TO_INT macro to convert the strongly typed enum value b::B2 to int std::cout << TO_INT(b::B2) << std::endl; }</code>
While it's possible to convert strongly typed enums to ints without explicit casts, it's important to note that this may lead to unintended behavior. It's recommended to use explicit casts whenever appropriate to avoid potential issues.
The above is the detailed content of How to Implicitly Convert Strongly Typed Enums to Ints in C ?. For more information, please follow other related articles on the PHP Chinese website!