Home > Backend Development > C++ > body text

How to Cast Strongly Typed Enums to Integers in Modern C ?

Mary-Kate Olsen
Release: 2024-11-04 11:00:30
Original
1015 people have browsed it

How to Cast Strongly Typed Enums to Integers in Modern C  ?

How to Cast Strongly Typed Enums to Integers Seamlessly

Classically, enums could be implicitly converted to integer types, facilitating convenient usage. However, strongly typed enums, introduced in C 11, do not offer this flexibility without explicit casting. This difference stems from the intention to prevent accidental implicit conversions, upholding the safety measures of modern C .

To achieve the desired conversion without manual casting, you have two options:

  • Define a Template Function:

Define a generic template function that automatically retrieves the underlying type of an enum and performs the conversion. This approach eliminates the need to specify the target type in the cast:

<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

Usage:

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

This approach involves casting the strongly typed enum value to an instance of its underlying type using std::underlying_type:

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

While the first option provides greater flexibility and type safety, the second option is more straightforward and concise. Both methods offer effective ways to seamlessly convert strongly typed enum values to integers, aligning with the modern C philosophy of explicit type conversions.

The above is the detailed content of How to Cast Strongly Typed Enums to Integers in Modern 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!