Home > Backend Development > C++ > body text

Can Strongly Typed Enums Be Automatically Converted to Integers in C ?

Mary-Kate Olsen
Release: 2024-11-03 22:30:03
Original
900 people have browsed it

Can Strongly Typed Enums Be Automatically Converted to Integers in C  ?

Automating Strongly Typed Enum to Integer Conversion

In C , enums come in two flavors: strongly typed enums and regular enums. Regular enums can be implicitly converted to integers, while strongly typed enums require an explicit cast. This raises the question: is there an automated way to convert strongly typed enums to integers without resorting to explicit casts?

The answer is no, and it's intentional. Strongly typed enums are designed to prevent the implicit conversion to integers. Essentially, the compiler ensures that you explicitly acknowledge the conversion from an enumerated value to an integer.

However, there is a workaround to avoid specifying the underlying type in the cast. By utilizing a template function, we can abstract away the cast's type specification.

<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

With this template function, the conversion can be achieved as follows:

<code class="cpp">std::cout << foo(to_underlying(b::B2)) << std::endl;</code>
Copy after login

This approach eliminates the explicit type specification in the cast, simplifying the conversion process while maintaining the desired behavior of enforced explicit conversion for strongly typed enums.

The above is the detailed content of Can Strongly Typed Enums Be Automatically Converted 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