Hacker News new | ask | show | jobs
by mehrdadn 1416 days ago
Ah sorry about that, thanks for the feedback! I can try to answer these here (and hopefully update the documentation as well when I get the chance):

- The problem is basically twofold. Part (a) is that there are no facilities for dealing with enums in C++. "Dealing with" could be anything, such as: bitwise-combining enums as flags, converting enums to/from strings, verifying that a given value is valid for an enum, decomposing flags into their constituent values, and anything else people might typically want to do with enums. Part (b) is that people end up manually writing enum-specific functions for these over and over again, and that often results in brittle and non-reusable code that quickly gets out of sync with the actual enum as it evolves over time (e.g., handwritten parsing code might stop working when a new member is added). This library aims to address most if not all of these problems.

- There are 3 main "tricks" I've used (and a ton of boilerplate on top of that): (a) I use the auto-return-type-with-hidden-friends trick to "tag" the enum with metadata for later retrieval, (b) I overload the comma operator to be able to utilize the same text for both the enum definition as well as for storing relevant metadata, and (c) I use constexpr string parsing to extract the enum names from the definition passed to the macro. Part (a) is confusing and better explained in the link I put in the credits. Part (b) is somewhat tricky but hopefully not too bad. Part (c) seems obvious in hindsight now that I mention it, but I haven't seen it used elsewhere in this manner. (Edit: While digging further just now, I found someone has indeed tried a similar approach with constexpr string parsing in [1], though it appears less comprehensive.)

- No other libraries that I'm aware of support all the features of this one. Typical restrictions include: limiting the ranges of the underlying values, limiting the number of enumerators to some amount, not supporting enum members with duplicate values, not supporting 'enum class', etc.

Hope this helps! If I can clarify anything else please let me know.

[1] https://github.com/therocode/meta_enum/blob/master/include/m...

2 comments

One other thing that have felt the need to solve was iteration through the values as if it was a container, i.e. using the range-based for loop.
That's supported here! You can do:

  for (auto const &member : enum_traits<E>::members())
  { std::cout << member.name() << std::endl; }
Excellent, thanks. It'd already help if you put this answer on the readme page verbatim.