簡體   English   中英

如何查找給定字符串的ENUM類型?

[英]How to look up the ENUM type given a string?

我有一個像這樣的枚舉類:

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_strxmlXML ,那么我需要這樣設置:

TestClass::SetContentType(ContentTypeEnum::XML)

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

查找給定字符串的確切枚舉類型的正確方法是什么?

我建議編寫一個返回給定字符串的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM