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

后端 未结 28 2332
逝去的感伤
逝去的感伤 2020-11-22 16:57

Contrary to all other similar questions, this question is about using the new C++ features.

  • 2008 c Is there a simple way to convert C++ enum to string?
  • <
28条回答
  •  甜味超标
    2020-11-22 17:18

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

    #include 
    
    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_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 
      
      enum number { one = 100, two = 200, three = 300 };
      
      namespace magic_enum {
      template <>
        struct enum_range {
          static constexpr int min = 100;
          static constexpr int max = 300;
      };
      }
      

提交回复
热议问题