Subject: Re: [boost] Is there interest in a library for string-convertible enums?
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2014-10-28 19:57:00


On 29/10/2014 00:09, Felix Uhl wrote:
> So far, the only way to convert an enumeration value to a string is
> a lot of boilerplate code consisting of switch case statements for
> every single possible value of the enum.

Not the only way. The method I use is to create a lookup table via a
little macro magic. Granted that I'm then doing a linear scan through
the table (whereas a switch statement could be more efficient, or
knowledge that the enum is contiguous and could therefore do an index
lookup), but having a table allows for other useful queries, and I
wanted something that could be defined statically.

As a side-benefit (that undoubtedly will horrify some people), the way
the code was implemented also allows it to act as a
string-to-member-pointer lookup table, which can be quite handy for
typed property bags and the like with a string lookup key.

> What features would you want from such a library?

Features that I would expect of such a library:

  - support for arbitrary non-contiguous values.
  - enum value to string.
  - string to enum value.
  - list of all valid values, either as strings or values.
  - can indicate whether a given value (string or enum) is a member of
the enumeration.
  - can round-trip (enum -> string -> enum) values that are not members
of the enumeration; of course (string -> enum -> string) is not feasible
for non-members.
  - can specify a custom string value that the enum value generates (not
just the BOOST_PP_STRINGIZE).

Features that would be nice, but not necessarily expected:

  - enum to string and back for "bitwise flag" style enums (eg. CSV names).
  - some mapping to std::bitset or similar.
  - can specify multiple string values that map to the same enum value.
  - can specify different conversion tables for the same enum type (for
use in different contexts, eg. serialisation vs. user output).