将C ++枚举为const char *

时间:2012-12-13 07:15:31

标签: c++ map

我有以下枚举和地图:

typedef enum {
    MaxX = 0,
    MaxY,
    MaxCells,
    MaxCycles,
    Threes
} SettingName;

typedef std::map<SettingName, const char*> SettingNameCollection;

SettingNameCollection settingNames;

我有以下函数来返回枚举名称:

const char* gofBoard::getSettingName(unsigned x) {
    return settingNames[static_cast<SettingName>(x)];
}

从我读过的内容应该可行,但该功能不会返回任何内容。没有编译时错误,也没有运行时错误。

5 个答案:

答案 0 :(得分:4)

这是我的建议:

1-写下这个宏:

#define SMART_STRINGIFY_CASE(ENUM_CODE) case ENUM_CODE: return # ENUM_CODE

2-写这个功能:

const char* SettingNamesToString( settingNames const input)
{
  switch(input)
  {
    SMART_STRINGIFY_CASE(MaxX);
    SMART_STRINGIFY_CASE(MaxY);
    ...
  default:
    // your own ! 
}

答案 1 :(得分:1)

operator[]用于在std :: map中检索/插入数据。您可能对std::map::find

感到更舒服
const char* gofBoard::getSettingName(unsigned x) {
    auto found = settingNames.find(static_cast<SettingName>(x));
    if (found == settingNames.end())
        /* throw appropriate exception */
    /* or assert */
    assert ( found != settingNames.end() );
    return found->second;
}
编辑:就像有人说的那样,为了你的目的,一个简单的std::array就足够了。

答案 2 :(得分:0)

如果在调用该函数之前没有填充地图,那么你得到的不是错误,它是一个空白字符串(我猜)

你想做这样的事情

typedef std::array<const char*,Threes+1> SettingNameCollection;  
// usually for such purposes, sometimes an extra enum is added to give you number of valid enum values ( Settings_Num for instance)

SettingNameCollection settingNames {
    "MaxX ",
    .....
    "Threes",
}; // first time using the new syntax, is this correct?

const char* gofBoard::getSettingName(SettingName setting) {
    return settingNames[setting]; //do i need to cast to int in c++11?
}

答案 3 :(得分:0)

如果你的枚举是连续的,那么map肯定是矫枉过正的。我建议切换到macro definition

摘录:

SANDBOX_DEFINE_ENUM(MyEnum, (Foo)(Bar)(Team))

将扩展为:

struct MyEnum {
  enum Type {
    Foo,
    Bar,
    Team
  };
  static Type const First = Foo;
  static Type const Last = Team;
};

inline char const* toString(MyEnum::Type value) {
  switch(value) {
  case MyEnum::Foo: return "Foo";
  case MyEnum::Bar: return "Bar";
  case MyEnum::Team: return "Team";
  }
  return 0;
}

答案 4 :(得分:0)

每个用C ++编程的人都遇到了枚举到字符串转换(以及字符串到枚举转换)的问题。需要考虑各种方面来很好地解决问题,例如,如果请求无效枚举的字符串该怎么办?我认为通过使用可用于大部分或全部枚举的通用解决方案,您将受益匪浅。这个问题涵盖了这个问题:

Which Typesafe Enum in C++ Are You Using?