我有一个这样的枚举类:
class ContentTypeEnum {
public:
// it might have more types
enum Code { TEXT, XML, APPLICATION_JSON};
static const char* to_c_str(unsigned);
};
到目前为止,我在我的代码中使用它。
ContentTypeEnum::APPLICATION_JSON
问题陈述:-
现在我有一个字符串,所以我需要使用该字符串,然后通过迭代上面的枚举来找到实际的 ENUM 类型。
下面是我的代码:
cout<<"Given String: " << data_args->pp_args->ter_strings[0].c_str() << endl;
const char* test_str = data_args->pp_args->ter_strings[0].c_str();
现在如果test_str
是xml
or XML
,那么我需要这样设置:
TestClass::SetContentType(ContentTypeEnum::XML)
但是如果test_str
是application_json
or APPLICATION_JSON
,那么我需要这样设置:
TestClass::SetContentType(ContentTypeEnum::APPLICATION_JSON)
对其他人也是如此。以下是我的完整代码:
cout<<"Given String: " << data_args->pp_args->ter_strings[0].c_str() << endl;
char* test_str = data_args->pp_args->ter_strings[0].c_str();
// look up the exact ContentType from the enum using test_str string
// and then set it to below method.
TestClass::SetContentType(set_it_here_basis_on_string_test_str)
如果有人传递了我的枚举中不存在的任何未知字符串,那么它应该默认使用TestClass::SetContentType(ContentTypeEnum::APPLICATION_JSON)
给定字符串查找确切枚举类型的正确方法是什么?