Settings

Theme

Show HN: Generate code for pretty-printing C++ enums

github.com

2 points by aburdulescu 4 years ago · 1 comment

Reader

greggman3 4 years 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

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection