C++的枚举转字符串中常用的方法
C++的枚举转字符串中常用的方法一般是写switch case或者直接写if else判断,这种方式就没那么优雅了
通用的方法
废话不多说直接上代码
// enum_to_string.h
#ifndef ENUM_TO_STRING_H
#define ENUM_TO_STRING_H
#include <string>
#include <unordered_map>
#include <type_traits>
// toString函数模板的正向声明
template <typename Enum>
std::string toString(Enum e);
// 将枚举映射到字符串的实用工具模板
template <typename Enum>
struct EnumToString
{
static const std::unordered_map<Enum, std::string>& getEnumToStringMap()
{
static const std::unordered_map<Enum, std::string> enumToStringMap;
return enumToStringMap;
}
};
// 宏来帮助定义类作用域中每个枚举的映射
#define DEFINE_ENUM_TO_STRING(EnumType, ...) \
template <> \
struct EnumToString<EnumType> \
{ \
static const std::unordered_map<EnumType, std::string>& getEnumToStringMap() \
{ \
static const std::unordered_map<EnumType, std::string> enumToStringMap = __VA_ARGS__; \
return enumToStringMap; \
} \
};
// toString函数模板的实现
template <typename Enum>
std::string toString(Enum e)
{
static_assert(std::is_enum<Enum>::value, "Template parameter is not an enum type");
const auto& map = EnumToString<Enum>::getEnumToStringMap();
auto it = map.find(e);
if (it != map.end())
{
return it->second;
}
return "Unknown";
}
#endif // ENUMTOSTRING_H
使用的时候,需要在有枚举的地方增加类似如下代码
// MyEnums.h
#ifndef MYENUMS_H
#define MYENUMS_H
#include "EnumToString.h"
class MyClass
{
public:
enum class Color
{
Red,
Green,
Blue
};
};
DEFINE_ENUM_TO_STRING(MyClass::Color, {
{MyClass::Color::Red, "Red"},
{MyClass::Color::Green, "Green"},
{MyClass::Color::Blue, "Blue"}
})
#endif
使用DEFINE_ENUM_TO_STRING来列举出里面的类
使用的时候,直接就可以使用toString函数
// main.cpp
#include <iostream>
#include "MyEnums.h"
int main()
{
MyClass::Color color = MyClass::Color::Red;
std::cout << "Color: " << toString(color) << std::endl;
return 0;
}