0

我有一个这样的枚举类:

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_strxmlor XML,那么我需要这样设置:

TestClass::SetContentType(ContentTypeEnum::XML)

但是如果test_strapplication_jsonor 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)

给定字符串查找确切枚举类型的正确方法是什么?

4

1 回答 1

4

我建议编写一个返回enum给定字符串的函数。

Code getCode(std::string const& s)
{
   static std::map<std::string, Code> theMap{{"TEXT", TEXT},
                                             {"XML", XML}
                                             {"APPLICATION_JSON", APPLICATION_JSON}};

   std::map<std::string, Code>::iterator it = theMap.find(s);
   if ( it != theMap.end() )
   {     
      return it->second;
   }
   return APPLICATION_JSON;
}
于 2015-04-21T22:09:18.883 回答