boost::bimap for enum
Asked Answered
M

1

6

I'm trying to create a simple bi-directional lookup facility for enums in C++. I have one-way lookup working fine...

enum MyEnum
{ 
    One, 
    Two, 
    Three 
};

const boost::unordered_map<MyEnum,std::string> MyEnumMap = map_list_of
    (One, "One")
    (Two, "Two")
    (Three, "Three");

and then doing a look via

MyEnumMap.at(One)

That works but it only allows for lookups based on key. I'd like to use a bi-directional lookup container such as boost:bimap to allow for easy reverse lookups based on value as well as key. It doesn't seem like map_list_of is compatible with boost::bimap though.

Firstly, should I still be using map_list_of with boost::bimap, or is another type required?
The maps will all be a basic (Enum, string) type.

Second, is there a way I can still define the map as const in a simple way as above? I'm trying to make this as easy to update and maintain as possible without getting into too many additional typedefs and such. Your insight is appreciated.

Muntjac answered 24/5, 2012 at 21:37 Comment(1)
if you are just interested in a good way to map enumerators to strings, you could take advantage of boost_enum (from the boost vault). Look this thread : #218049Giselagiselbert
H
13

Try using list_of directly:

typedef boost::bimap< MyEnum, std::string > bm_type;
const bm_type MyEnumMap =
  boost::assign::list_of< bm_type::relation >
    ( One, "One" )
    ( Two, "Two" )
    ( Three, "Three" );

Note the usage of 'relation' instead of 'value_type'.

Huddleston answered 24/5, 2012 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.