Search code examples
c++enumsc-str

How to look up the ENUM type given a string?


I have an enum class like this:

class ContentTypeEnum {

 public:

  // it might have more types
  enum Code { TEXT, XML, APPLICATION_JSON};

  static const char* to_c_str(unsigned);

};

I was using it like this in my code as of now.

ContentTypeEnum::APPLICATION_JSON

Problem Statement:-

Now I have a string given so I need to use that string and then find the actual ENUM type by iterating it my above enum.

Below is my code:

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();

Now if test_str is xml or XML, then I need to set it like this:

TestClass::SetContentType(ContentTypeEnum::XML)

But if test_str is application_json or APPLICATION_JSON, then I need to set it like this:

TestClass::SetContentType(ContentTypeEnum::APPLICATION_JSON)

And similarly for others as well. Below is my full code:

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)

If somebody is passing any unknown string which is not there in my enum, then it should use by default as TestClass::SetContentType(ContentTypeEnum::APPLICATION_JSON)

What is the right way to lookup the exact enum type given a string?


Solution

  • I suggest writing a function that returns the enum given a string.

    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;
    }