Home >Backend Development >C++ >How to Explicitly Convert Strongly Typed Enums to Integers in C ?

How to Explicitly Convert Strongly Typed Enums to Integers in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 12:55:02681browse

How to Explicitly Convert Strongly Typed Enums to Integers in C  ?

Automatically Converting a Strongly Typed Enum into Integer Type

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn