Show HN: Generate code for pretty-printing C++ enums
github.comPersonally 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