Home > Backend Development > C++ > How to Convert Enums to Strings and Vice Versa in Modern C ?

How to Convert Enums to Strings and Vice Versa in Modern C ?

DDD
Release: 2024-12-22 03:03:14
Original
839 people have browsed it

How to Convert Enums to Strings and Vice Versa in Modern C  ?

Converting Enum to String in Modern C

To convert an enum to a string in modern C , leverage the Magic Enum header-only library for static reflection on enums.

#include <magic_enum.hpp>

enum Color { RED = 2, BLUE = 4, GREEN = 8 };

// Convert enum value to string
auto color_name = magic_enum::enum_name(Color::RED);

// Convert string to enum value
std::string color_name = "GREEN";
auto color = magic_enum::enum_cast<Color>(color_name);
Copy after login

Considerations

  • Magic Enum requires a compiler-specific hack and operates within a predefined numeric range, typically [-128, 128].
  • Customize the range for all enum types by modifying MAGIC_ENUM_RANGE_MIN and MAGIC_ENUM_RANGE_MAX.
  • Specify a custom range for specific enum types using enum_range specialization.

The above is the detailed content of How to Convert Enums to Strings and Vice Versa 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template