0

I need to define an enum like ID and also provide converting utility for it to the corresponding string and vice versa. So I am choosing unordered_map to save such 1-on-1 mapping. It effectively would translate to belowing:

enum COLOR_ID {
    UNKNOWN,
    GREEN,
    RED,
    BLUE,
    YELLOW
};

std::unordered_map<std::string, COLOR_ID> str_id_map;
str_id_map["GREEN"] = GREEN;
...

std::unordered_map<COLOR_ID, std::string, COLOR_ID> id_str_map;
id_str_map[GREEN] = "GREEN";
...

The reason I am doing this is I will have a very long and expandable list of enums/IDs, and I want to make it easy to maintain to add a new enum/ID. The user only need to add the ID in one place, and it gets automatically populated to the two maps.

Any ideas?

I wonder whether there is a more succinct way to use a MACRO that I can only give the COLOR_ID list once instead putting it in three places, so that would be easier to maintain.

6
  • You might want to try this: github.com/Neargye/magic_enum Commented Nov 30, 2021 at 15:16
  • 1
    You don't need typedef in C++ for enumerations. The enumeration name is itself a type-name, so enum COLOR_ID { ... }; is enough. Commented Nov 30, 2021 at 15:21
  • Also note note that all-uppercase names are usually used for only for macros. Commented Nov 30, 2021 at 15:23
  • In C++ you should only use MACRO's as a last resort. Usually you can solve things with: functions, constexpr (compile time) functions and/or template classes/functions. These will all be more typesafe and better to debug! For example : onlinegdb.com/IEBs299H-H Commented Nov 30, 2021 at 15:37
  • If you do use a helper macro here (not recommended), #define it within the function, and then #undef it before the end of the function. Only you can prevent forest fires. Commented Nov 30, 2021 at 15:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.