Home >Backend Development >C++ >How to Explicitly Convert Strongly Typed Enums to Integers in C ?
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);</int></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>::type>(e); }</typename></e></typename></code>
Now, the conversion can be performed without specifying the underlying type explicitly:
<code class="cpp">std::cout <p>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.</p></code>
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!