Boost logo

Boost :

Subject: [boost] enum / string translation
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-07-21 23:42:46

I wrote some code to perform both compile-time and runtime translation
between enums and their corresponding string values. The only
direction that isn't possible is string->enum at compile time.

Is there any interest in this? You can use it as follows:

typedef enum { ValueA1, ValueA2 } EnumA;
typedef enum { ValueB1, ValueB2 } EnumB;

   BEGIN_ENUM_MAP(EnumA, a_map)
      ENUM_MAP(ValueA1) //maps ValueA1 to the string "ValueA1",
provides both compile-time and run-time lookups.
      ENUM_MAP_NAME(ValueA2, "custom name") //maps ValueA2 to the
string "custom name", provides both compile-time and run-time lookups

   BEGIN_ENUM_MAP(EnumB, b_map)

void foo()
   //value -> string, compile time
   BOOST_STATIC_ASSERT(enum_map<EnumA>::value_lookup[ValueA2] == "custom name");

   //value -> string, runtime
   EnumB some_value = get_enum_b_from_external_source();
   std::cout << "some_value = " <<
enum_map<EnumB>::name_lookup[some_value] << std::endl; //prints
either 'some_value = ValueB1', or 'some_value = ValueB2'

   //string -> value, runtime
   EnumA value = enum_map<EnumA>::name_lookup["custom name"];
   BOOST_ASSERT(value == ValueA2);

One particularly useful application of this that I've found is with
regards to boost::program_options. You can provide an overload of
boost::program_options::validate that uses boost::enable_if with
boost::is_enum thus providing automatic support for entry of friendly
names corresponding to enumerations on the command line or in a config
file. Obviously there's many other easily identifiable uses as well.

However, this is a common enough problem that I wonder if anyone else
has already attempted something like this, and if so maybe I can look
at their code first, or just scrap mine altogether and reuse something
existing. If not, I'm sure there is plenty of room for improvement in
mine but if it could fit somewhere in boost (perhaps boost/utility)
I'd be willing to submit it and make necessary improvements.

Unfortunately I don't think it's technically possible to have a simple
syntax, even through preprocessor magic, that requires you to only
specify the name of each enumerated value once, and end up providing
both a definition of the enumeration as well as the mapping from
string<->value, but if someone comes up with a way that would
obviously be ideal.

Boost list run by bdawes at, gregod at, cpdaniel at, john at