Home > Backend Development > C++ > body text

How to Implicitly Convert Strongly Typed Enums to Ints in C ?

Susan Sarandon
Release: 2024-11-04 12:28:01
Original
642 people have browsed it

How to Implicitly Convert Strongly Typed Enums to Ints in C  ?

Implicit Conversion of Strongly Typed Enums to Int

Strongly typed enums, introduced in C 11, are designed to prevent implicit conversions to integers. However, there may be cases where you want to convert a strongly typed enum value to an int without an explicit cast.

To address this, several approaches have been suggested:

  1. Using a Function:

You can define a function that performs the conversion. For instance:

<code class="cpp">#include <iostream>

struct a {
  enum LOCAL_A { A1, A2 };
};

template <typename E>
int to_int(E e) {
  return static_cast<int>(e);
}

int main() {
  // Use the to_int function to convert the strongly typed enum value b::B2 to int
  std::cout << to_int(b::B2) << std::endl;
}</code>
Copy after login
  1. Using a Function with Template Argument Deduction:

To simplify the syntax, you can use a function template that automatically deduces the enum type:

<code class="cpp">#include <iostream>

struct a {
  enum LOCAL_A { A1, A2 };
};

template <typename E>
constexpr typename std::underlying_type<E>::type get_underlying(E e) noexcept {
  return static_cast<typename std::underlying_type<E>::type>(e);
}

int main() {
  // Use the get_underlying function to convert the strongly typed enum value b::B2 to int
  std::cout << get_underlying(b::B2) << std::endl;
}</code>
Copy after login
  1. Creating a Macro:

You can also utilize a macro to make the conversion process more concise:

<code class="cpp">#include <iostream>

struct a {
  enum LOCAL_A { A1, A2 };
};

#define TO_INT(e) static_cast<int>(e)

int main() {
  // Use the TO_INT macro to convert the strongly typed enum value b::B2 to int
  std::cout << TO_INT(b::B2) << std::endl;
}</code>
Copy after login

While it's possible to convert strongly typed enums to ints without explicit casts, it's important to note that this may lead to unintended behavior. It's recommended to use explicit casts whenever appropriate to avoid potential issues.

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