4 ms·
> you can use various preprocessor tricks to implement getEnumName such that you don't have to change it when adding more cases to the enum. For those who don’
by Someone 5y ago
> you can use various preprocessor tricks to implement getEnumName such that you don't have to change it when adding more cases to the enum.
For those who don’t know: the X Macro (https://en.wikipedia.org/wiki/X_Macro https://en.wikipedia.org/wiki/X_Macro, https://digitalmars.com/articles/b51.html https://digitalmars.com/articles/b51.html)
- OskarS 5y agoHey, even an article written by Walter, that's a fun coincidence! :) This is slightly different than the form I've seen it, but same idea: in the version I've seen, you have a special file that's like "enums.txt" with contents like (warning, not tested): X(red) X(green) X(blue) and then you write: typedef enum { #define X(x) x #include "enums.txt" #undef X } color; const char* getColorName(color c) { switch (c) { #define X(x) case x: return #x; #include "enums.txt" #undef X } } Same idea, just using an #include instead of listing them in a macro. Thinking about it, it's sort-of a compile time "visitor pattern".
- WalterBright 5y agoAs an update, I removed all use of the X macro in my own code.