在c ++中将char*转换为枚举

esw*_*aat 1 c c++ enums

我想转换char *enum所以我使用了这个.但转换char *到时我收到错误enum

我不能改变我的enum.也是type[]动态的简化我显示静态值.

enum type_t {
    MSG_1 = 0,
    MSG_2
};

char type[] = "MSG_1|MSG_2";
char *type_char;
type_char = strtok (type,"|");
while (type_char != NULL)
{
    type_t type_enum = static_cast<type_t >(type_char );
    type_char = strtok (NULL, "|;");
}
Run Code Online (Sandbox Code Playgroud)

我收到了以下错误

error: invalid static_cast from type 'char*' to type 'type_t'
Run Code Online (Sandbox Code Playgroud)

我想转换char *enum

das*_*ght 5

与其他具有更强运行时"反射"功能的语言不同,C++ enum中的纯粹是编译时工件.编译完成后,无法获取枚举常量的名称.调试器可以通过读取编译器为调试器准备的特殊表来获取它们,但访问这些文件会适得其反.

如果您希望能够枚举的名称转换为自己的价值观,做一个unordered_mapstring你的enum,填充它静态,并根据需要进行查询:

static std::unordered_map<std::string,type_t> nameToTypeT;
...
nameToTypeT["MSG_1"] = MSG_1;
nameToTypeT["MSG_2"] = MSG_2;
...
type_t = nameToTypeT[std::string(type_char)];
Run Code Online (Sandbox Code Playgroud)