C++ string to enum

前端 未结 12 1298
无人及你
无人及你 2020-11-29 12:01

Is there a simple way in C++ to convert a string to an enum (similar to Enum.Parse in C#)? A switch statement would be very long, so I was wondering i

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 12:31

    A std::map (or unordered_map) could do it easily. Populating the map would be just as tedious as the switch statement though.

    Edit: Since C++11, populating is trivial:

    static std::unordered_map const table = { {"a",E::a}, {"b",E::b} };
    auto it = table.find(str);
    if (it != table.end()) {
      return it->second;
    } else { error() }
    

提交回复
热议问题