c++ - 枚举作为参数返回字符串

标签 c++ string enums

我当前的程序使用了 3 个不同的枚举:

enum ThingEnum{
    Thing1 = 0,
    Thing2 = 1,
    Thing3 = 2,
    OtherThing = 3
};
enum ReturnEnum {
    Success = 4,// the method did what it is supposed to
    Error1 = 5,// an error occured
    Error2 = 6,// an error occured
    Error3 = 7,// an error occured
    Error4 = 8,// a fatal error occured program must terminate
    Pointer = 9// the method may need to be called again
};
enum TypeEnum {
    Type1 = 10,
    Type2 = 11,
    Type3 = 12,
    Type4 = 13,
    OtherType = 14
};  

我想做的是创建一个全局函数,它接受一个枚举并返回一个字符串(因为枚举的值实际上只是一个始终有值的专用变量名)。 是否可以创建一个采用通用枚举的函数?例如

string enumToString (enum _enum){}

或者我必须为每个不同的枚举创建一个函数吗?只是一个可能的想法,我做了一些阅读,一些编译器允许 Enum 解析为 int,所以我可以将 enum 作为 int 传递,然后使用它吗?

最佳答案

“ToString-like”函数实现有两种选择:

  1. 实现一个简单的静态 switch-case 函数。

代码:

std::string ThingEnumToString(ThingEnum thing)
{
    switch (thing) {
    case Thing1:
        return std::string("Thing1");
    case Thing2:    
        return std::string("Thing2");
    case Thing3:
        return std::string("Thing3");        
    case OtherThing:
        return std::string("OtherThing");
    default:
        throw std::invalid_argument("thing");
        break;
    }
}
  1. 通过字典查找实现静态函数。

代码:

typedef std::map<ThingEnum, std::string> ThingsMap;

static ThingsMap GetThingsMap()
{
    ThingsMap things_map;
    things_map.insert(ThingsMap::value_type(Thing1, std::string("Thing1")));
    things_map.insert(ThingsMap::value_type(Thing2, std::string("Thing2")));
    things_map.insert(ThingsMap::value_type(Thing3, std::string("Thing3")));
    things_map.insert(ThingsMap::value_type(OtherThing, std::string("OtherThing")));
    return things_map;
}

static std::string ThingEnumToString(ThingEnum thing)
{
    static const ThingsMap things(GetThingsMap());
    ThingsMap::const_iterator it = things.find(thing);
    if (it != things.end()) {
        return it->second;
    } else {
        throw std::invalid_argument("thing");
    }
}

关于c++ - 枚举作为参数返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9111688/

相关文章:

sql - 统计一个字符在 Oracle SQL 中出现的次数

java - 从字符串构造函数获取枚举值

c++ - 调用定义函数时在QT Creator中获取 "undefined reference"

c# - 用 C++ 编写的存储结构和类在哪里?

c++ - 我可以将 Boost 源代码+头文件添加到我自己的(开源)项目中吗?

c# - 在 C# 中实现与 CTime.GetTime() 方法相同的行为

c++ - 将 std::string 传递给 C 风格的 API 是否安全?

ios - Swift 2 如何更改公共(public) var 字符串

在 switch 中捕获混合枚举

c++ - 在 C++ 中使用枚举进行面向整数位的操作是否可靠/安全?