Boost logo

Boost :

Subject: Re: [boost] enum / string translation
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-07-27 14:04:34


On Mon, Jul 27, 2009 at 9:54 AM, Stewart, Robert<Robert.Stewart_at_[hidden]> wrote:
> Fatih wrote:
>>
>> I'm very interesting in this problem ,I think it's very hard
>> to implement
>> the string to enum translation at compile time,  I have no
>> ideas about it,
>> wish you can work it out.
>
> It is not difficult, though it requires registering the string against the value in a map during runtime initialization.  (We use a library initialization mechanism, called from main(), to trigger such initialization.)

Well that's of course not a compile time solution though if it
requires runtime initialization.

The approach taken by my solution (which I still haven't uploaded to
vault btw) scopes the enums with a namespace, and inside the namespace
provides a template specialization for each value in the enum that was
specified by one of the MAP_ENUM() macro invocations. For example,
given the followign enum definition:

typedef enum { Value1, Value2 } Enum1;

Then the macro sequence:

BEGIN_ENUM_MAP(Enum1, map1)
ENUM_MAP(Value1, "this is a test")
ENUM_MAP(Value2, "test2")
END_ENUM_MAP()

would generate the following code:

namespace map1
{
   template<Enum1 e> class lookup {};

   template<>
   class lookup<Value1> { static const char* name; };
   const char* lookup<Value1>::name = "this is a test";

   template<>
   class lookup<Value2> { static const char* name; };
   const char* lookup<Value2>::name = "test2";
}

Now, using code such as the following:

std::string test = map1::lookup<Value1>::name;

which with optimizations on will generate identical code as doing:

std::string test = "test2";

Of course my macros generated additional code as well to create and
initialize static runtime lookup maps, but due to the inclusion of
everything in every translation unit I agree it's not appropriate in
its current form. When I get time to re-think about it perhaps I'll
address that issue and then consider uploading it.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk