There are plenty solutions how to get text representation of an enum as string with use of C++ proprocessor (for example this topic).
However, I would like to do the conversion in opposite direction in order to mimick switch on strings.
So for example - given the following enum:
typedef enum { RIGHT, LEFT, FORWARD, BACKWARD} direction;
For small enums, one could define array of strings and use enum values to get the appropriate string, but that is bad for maintanance.
I would like to have some macro which would define a function "direction FromString(char * str)", which would return RIGHT if I have a string "RIGHT".
There are many sollutions for other programming languages like C# or Java, so I don't think that would be such a bad practice.
There is a similar question to mine, but without using preprocessor.
My current sollution (based on one of the answers to another question) looks like this:
#include <boost/preprocessor.hpp>
#define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOENUM(r, data, elem) \
if (!strcmp(s, BOOST_PP_STRINGIZE( elem ))) return elem;
#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators) \
enum name { \
BOOST_PP_SEQ_ENUM(enumerators) \
}; \
inline const name FromString(char * s) { \
BOOST_PP_SEQ_FOR_EACH( \
X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOENUM, \
name, \
enumerators \
) \
return ERR; \
}
One can use it by:
DEFINE_ENUM_WITH_STRING_CONVERSIONS(direction, (RIGHT)(LEFT)(...)(ERR))
The downside is that one has to include ERR to handle the case when the string does not match any of the enum names. How to avoid this?
I was thinking, that maybe a much more elegant sollution would be to use Boost Bimap.