In C , strongly typed enums ensure greater type safety than traditional enums. However, unlike traditional enums, strongly typed enums cannot be implicitly converted to integer types.
To convert a strongly typed enum value E into an integer type, an explicit cast is required, such as:
<code class="cpp">int i = static_cast<int>(b::B2);</code>
However, if the underlying type of the enum is unknown, the following template function can be used:
<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>
Now, the conversion can be performed without specifying the underlying type explicitly:
<code class="cpp">std::cout << foo(to_underlying(b::B2)) << std::endl;</code>
It's important to note that this conversion only works for values of strongly typed enums. If a traditional enum value is provided to to_underlying(), an error will be raised.
The above is the detailed content of How to Explicitly Convert Strongly Typed Enums to Integers in C ?. For more information, please follow other related articles on the PHP Chinese website!