C++ 字符串枚举

2021-12-29 00:00:00 string enums c++

C++ 中是否有一种简单的方法可以将字符串转换为枚举(类似于 C# 中的 Enum.Parse)?switch 语句会很长,所以我想知道是否有更简单的方法来做到这一点?

Is there a simple way in C++ to convert a string to an enum (similar to Enum.Parse in C#)? A switch statement would be very long, so I was wondering if there is a simpler way to do this?

感谢您的所有回复.我意识到对于我的特殊情况,有一种更简单的方法可以做到这一点.字符串总是包含字符 'S' 后跟一些数字,所以我只是做了

Thanks for all of your replies. I realized that there was a much simpler way to do it for my particular case. The strings always contained the charater 'S' followed by some number so i just did

int i = atoi(myStr.c_str() + 1);

然后打开 i.

推荐答案

A std::map(或 unordered_map)可以做它很容易.填充地图和 switch 语句一样乏味.

A std::map<std::string, MyEnum> (or unordered_map) could do it easily. Populating the map would be just as tedious as the switch statement though.

编辑:从 C++11 开始,填充是微不足道的:

Edit: Since C++11, populating is trivial:

static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} };
auto it = table.find(str);
if (it != table.end()) {
  return it->second;
} else { error() }

相关文章