一个C++的枚举转字符串通用的工具函数

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值