
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.
Download the .hpp file:
curl -LO https://github.com/Neargye/magic_enum/raw/master/include/magic_enum/magic_enum.hppInstall cURL, e.g.:
sudo apt install curl
wget -4 https://github.com/Neargye/magic_enum/raw/master/include/magic_enum/magic_enum.hppInvoke-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"For our examples we will use this enum:
enum Color {
RED,
GREEN,
BLUE
};std::string str = magic_enum::enum_name(Color::GREEN).data();auto color = magic_enum::enum_cast<Color>("GREEN");
if(color.has_value()){
// color.value() is Color::GREEN
}
for(auto color : magic_enum::enum_values<Color>()){
std::cout << magic_enum::enum_name(color) << '\n';
}constexpr std::size_t color_count = magic_enum::enum_count<Color>(); // 3
bool is_valid = magic_enum::enum_contains<Color>(2); // trueauto index = magic_enum::enum_index(Color::BLUE); // two
auto color = magic_enum::enum_value<Color>(index.value()); // Color::BLUEThe 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.