How to Cast Strongly Typed Enums to Integers Seamlessly
Classically, enums could be implicitly converted to integer types, facilitating convenient usage. However, strongly typed enums, introduced in C 11, do not offer this flexibility without explicit casting. This difference stems from the intention to prevent accidental implicit conversions, upholding the safety measures of modern C .
To achieve the desired conversion without manual casting, you have two options:
Define a generic template function that automatically retrieves the underlying type of an enum and performs the conversion. This approach eliminates the need to specify the target type in the cast:
<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>
Usage:
<code class="cpp">std::cout << foo(to_underlying(b::B2)) << std::endl;
This approach involves casting the strongly typed enum value to an instance of its underlying type using std::underlying_type:
<code class="cpp">std::cout << foo(static_cast<std::underlying_type<b>::type>(b::B2)) << std::endl;</code>
While the first option provides greater flexibility and type safety, the second option is more straightforward and concise. Both methods offer effective ways to seamlessly convert strongly typed enum values to integers, aligning with the modern C philosophy of explicit type conversions.
The above is the detailed content of How to Cast Strongly Typed Enums to Integers in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!