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
Release: 2024-11-04 12:55:02
Original
649 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template