Show HN: Generate code for pretty-printing C++ enums (github.com) 2 points by aburdulescu 4y ago ↗ HN
[–] greggman3 4y ago ↗ Personally I hate adding dependencies to my builds so for this I use macro lists #define FOO_ENUMS \ ENUM_HELPER(Apple) \ ENUM_HELPER(Banana) \ ENUM_HELPER(Orange) \ ENUM_HELPER(Pear) \ #undef ENUM_HELPERP #define ENUM_HELPER(name) name; namespace test { enum Foo { FOO_ENUMS }; } #undef ENUM_HELPER #define ENUM_HELPER(name) #name, const char* fooEnumToString(const Foo v) { static const char* enumNames[] = { FOO_ENUMS }; return enumNames[v]; // may want to check v is in range } or if they aren't consecutive #undef ENUM_HELPERP #define ENUM_HELPER(name) case name: return #name; const char* fooEnumToString(const Foo v) { switch(v) { FOO_ENUMS default: return "*unknown*"; // or throw or assert etc.. } } I'm not alone. Major open source projects use this style. No dependencies required
1 comment
[ 310 ms ] story [ 484 ms ] thread