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.

xycs
  • 121
  • 1
  • 8
  • You might want to try this: https://github.com/Neargye/magic_enum – m88 Nov 30 '21 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. – Some programmer dude Nov 30 '21 at 15:21
  • Also note note that all-uppercase names are usually used for only for macros. – Some programmer dude Nov 30 '21 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 : https://onlinegdb.com/IEBs299H-H – Pepijn Kramer Nov 30 '21 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. – Eljay Nov 30 '21 at 15:45
  • You may want to use an array of names instead of a switch statement. You could also make a table of ``, which will help in conversion to and from enum. – Thomas Matthews Nov 30 '21 at 16:38

0 Answers0