与所有其他类似问题相反,这个问题是关于使用新的 C++ 特性。
看了很多答案,还是没有找到:
例子
一个例子通常比一个长的解释更好。
您可以在 Coliru 上编译并运行此代码段.
( Another former example 也可用)
#include <map>
#include <iostream>
struct MyClass
{
enum class MyEnum : char {
AAA = -8,
BBB = '8',
CCC = AAA + BBB
};
};
// Replace magic() by some faster compile-time generated code
// (you're allowed to replace the return type with std::string
// if that's easier for you)
const char* magic (MyClass::MyEnum e)
{
const std::map<MyClass::MyEnum,const char*> MyEnumStrings {
{ MyClass::MyEnum::AAA, "MyClass::MyEnum::AAA" },
{ MyClass::MyEnum::BBB, "MyClass::MyEnum::BBB" },
{ MyClass::MyEnum::CCC, "MyClass::MyEnum::CCC" }
};
auto it = MyEnumStrings.find(e);
return it == MyEnumStrings.end() ? "Out of range" : it->second;
}
int main()
{
std::cout << magic(MyClass::MyEnum::AAA) <<'\n';
std::cout << magic(MyClass::MyEnum::BBB) <<'\n';
std::cout << magic(MyClass::MyEnum::CCC) <<'\n';
}
约束#define
开销尽可能小。 enum
-> string
映射。 很高兴有
enum
从一个不为零的数字开始的值 enum
值 enum
值 class enum
(C++11) class enum : <type>
有任何允许 <type>
(C++11) 或者至少在运行时快速执行(例如
std::map
不是一个好主意...)constexpr
(C++11,然后在 C++14/17/20 中放宽)noexcept
(C++11) 一种可能的想法是使用 C++ 编译器功能在编译时使用基于
variadic template class
的元编程技巧生成 C++ 代码。和 constexpr
功能...
最佳答案
Magic Enum仅 header 库为 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
};
有关更多示例,请查看主存储库 https://github.com/Neargye/magic_enum .
缺点在哪里?
该库使用特定于编译器的 hack(基于
__PRETTY_FUNCTION__
/__FUNCSIG__
),适用于 Clang >= 5、MSVC >= 15.3 和 GCC >= 9。枚举值必须在
[MAGIC_ENUM_RANGE_MIN, MAGIC_ENUM_RANGE_MAX]
范围内.MAGIC_ENUM_RANGE_MIN = -128
, MAGIC_ENUM_RANGE_MAX = 128
. MAGIC_ENUM_RANGE_MIN
和 MAGIC_ENUM_RANGE_MAX
. MAGIC_ENUM_RANGE_MIN
必须小于或等于 0
并且必须大于 INT16_MIN
. MAGIC_ENUM_RANGE_MAX
必须大于 0
并且必须小于 INT16_MAX
. #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;
};
}
关于c++ - 在现代 C++11/C++14/C++17 和 future 的 C++20 中枚举到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828957/