Enum to String in Modern C++11/C++14/C++17 and Future C++20

enum to string in modern C++11 / C++14 / C++17 and future C++20

Magic Enum header-only library provides static reflection for enums (to string, from string, iteration) for C++17.

#include <magic_enum.hpp>

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

Color color = Color::RED;
auto color_name = magic_enum::enum_name(color);
// color_name -> "RED"

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

For more examples check home repository https://github.com/Neargye/magic_enum.

Where is the drawback?

This library uses a compiler-specific hack (based on __PRETTY_FUNCTION__ / __FUNCSIG__), which works on Clang >= 5, MSVC >= 15.3 and GCC >= 9.

Enum value must be in range [MAGIC_ENUM_RANGE_MIN, MAGIC_ENUM_RANGE_MAX].

  • By default MAGIC_ENUM_RANGE_MIN = -128, MAGIC_ENUM_RANGE_MAX = 128.

  • If need another range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN and MAGIC_ENUM_RANGE_MAX.

  • MAGIC_ENUM_RANGE_MIN must be less or equals than 0 and must be greater than INT16_MIN.

  • MAGIC_ENUM_RANGE_MAX must be greater than 0 and must be less than INT16_MAX.

  • If need another range for specific enum type, add specialization enum_range for necessary enum type.

    #include <magic_enum.hpp>

    enum number { one = 100, two = 200, three = 300 };

    namespace magic_enum {
    template <>
    struct enum_range<number> {
    static constexpr int min = 100;
    static constexpr int max = 300;
    };
    }

enum to string in modern C++11 / C++14 / C++17 and future C++20

Magic Enum header-only library provides static reflection for enums (to string, from string, iteration) for C++17.

#include <magic_enum.hpp>

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

Color color = Color::RED;
auto color_name = magic_enum::enum_name(color);
// color_name -> "RED"

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

For more examples check home repository https://github.com/Neargye/magic_enum.

Where is the drawback?

This library uses a compiler-specific hack (based on __PRETTY_FUNCTION__ / __FUNCSIG__), which works on Clang >= 5, MSVC >= 15.3 and GCC >= 9.

Enum value must be in range [MAGIC_ENUM_RANGE_MIN, MAGIC_ENUM_RANGE_MAX].

  • By default MAGIC_ENUM_RANGE_MIN = -128, MAGIC_ENUM_RANGE_MAX = 128.

  • If need another range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN and MAGIC_ENUM_RANGE_MAX.

  • MAGIC_ENUM_RANGE_MIN must be less or equals than 0 and must be greater than INT16_MIN.

  • MAGIC_ENUM_RANGE_MAX must be greater than 0 and must be less than INT16_MAX.

  • If need another range for specific enum type, add specialization enum_range for necessary enum type.

    #include <magic_enum.hpp>

    enum number { one = 100, two = 200, three = 300 };

    namespace magic_enum {
    template <>
    struct enum_range<number> {
    static constexpr int min = 100;
    static constexpr int max = 300;
    };
    }

How to convert an enum type variable to a string?

There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.

If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.

enum class of type string in C++

There is no way to do that in C++11 or C++14. However, you should consider having some enum class, then code some explicit functions or operators to convert it from and to std::string-s.

There is a class in C++11 known as enum class which you can store variables inside.

That phrasing is not correct: an enum class does not store variables (but enumerators).

So you might code:

enum class MyEnum : char {
v1 = 'x', v2 = 'y'
};

(this is possible, as answered by druckermanly, because char is an integral type; of course you cannot use strings instead)

then define some MyEnum string_to_MyEnum(const std::string&); function (it probably would throw some exception if the argument is an unexpected string) and another std::string MyEnum_to_string(MyEnum); one. You might even consider also having some cast operator calling them (but I don't find that readable, in your case). You could also define a class MyEnumValue containing one single data member of MyEnum type and have that class having cast operator, e.g.

 class MyEnumValue {
const MyEnum en;
public:
MyEnumValue(MyEnum e) : en(e) {};
MyEnumValue(const std::string&s)
: MyEnumValue(string_to_MyEnum(s)) {};
operator std::string () const { return MyEnum_to_string(en);};
operator MyEnum () const { return en };
//// etc....
};

With appropriate more things in MyEnumValue (see the rule of five) you might almost always use MyEnumValue instead of MyEnum (which perhaps might even be internal to class MyEnumValue)

Resolve enum class variable name to string

Is there any place where enum "name specifiers" are stored?

No, but one option is to use std::map<TestEnum, std::string> as shown below:

enum class TestEnum
{
None = 0,
Foo,
Bar
};
const std::map<TestEnum,std::string> myMap{{TestEnum::None, "None"},
{TestEnum::Foo, "Foo"},
{TestEnum::Bar, "Bar"}};

std::ostream& operator<< ( std::ostream& os, TestEnum aEnum )
{
os << myMap.at(aEnum);
return os;
}
int main()
{
std::cout << "This is " << TestEnum::Foo; //prints This is Foo
std::cout << "This is " << TestEnum::Bar; //prints This is Bar

return 0;
}

Demo

Enum to String C++

enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };

const char * getTextForEnum( int enumVal )
{
return EnumStrings[enumVal];
}


Related Topics



Leave a reply



Submit