How to use and what is the magic_enum library for

🪄 It provides advanced features that are not natively offered by the language.


How to use and what is the magic_enum library for


In the article about std::any we show, in addition to other information, how complicated it can be to convert enum to std::string and other types of operations. In this article we will learn about a header-only: magic_enum, which can greatly facilitate operations with enum

The magic_enum library is a useful tool for working with enums in C++. It provides advanced functionality that is not natively offered by the language. Here are some of the main features that magic_enum offers we will see in the examples.


Implementation

Download the .hpp file:

curl -LO https://github.com/Neargye/magic_enum/raw/master/include/magic_enum/magic_enum.hpp

Install cURL, e.g.: sudo apt install curl

  • Using GNU wget, you need to force IPv4:
wget -4 https://github.com/Neargye/magic_enum/raw/master/include/magic_enum/magic_enum.hpp
Invoke-WebRequest -Uri "https://github.com/Neargye/magic_enum/raw/master/include/magic_enum/magic_enum.hpp" -OutFile "magic_enum.hpp"

Add magic_enum.hpp to your code:

#include "./magic_enum.hpp"

Examples

For our examples we will use this enum:

enum Color {
 RED,
 GREEN,
 BLUE
};

1. Enum to String Conversion: Allows you to convert enum values to their corresponding string representations.

std::string str = magic_enum::enum_name(Color::GREEN).data();

2. String to Enum Conversion: Allows you to convert strings to enum values, if the string matches an enum value name.

auto color = magic_enum::enum_cast<Color>("GREEN");
if(color.has_value()){
 // color.value() is Color::GREEN
}


3. Iteration over Enum Values: Allows you to iterate over all values of an enum.

for(auto color : magic_enum::enum_values<Color>()){
 std::cout << magic_enum::enum_name(color) << '\n';
}

4. Get Enum Information: Provides functionality to get the number of values of an enum, check if a value is within the valid range, etc.

constexpr std::size_t color_count = magic_enum::enum_count<Color>(); // 3
bool is_valid = magic_enum::enum_contains<Color>(2); // true

5. Enum Indexing: Allows you to obtain the index of an enum value and vice versa.

auto index = magic_enum::enum_index(Color::BLUE); // two
auto color = magic_enum::enum_value<Color>(index.value()); // Color::BLUE

The magic_enum library is especially useful when you need introspection into enums, such as for serialization, debug, or code generation where you need to work with the names of enums values and their string representations. It simplifies the code and eliminates the need for manual maintenance of maps from enum to std::string and vice versa.

For more information, visit repository on GitHub.


cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles