The following solution is based on a std::array
for a given enum.
For enum
to std::string
conversion we can just cast the enum to size_t
and lookup the string from the array. The operation is O(1) and requires no heap allocation.
#include
#include
#include
#include
#include
#include
#define STRINGIZE(s, data, elem) BOOST_PP_STRINGIZE(elem)
// ENUM
// ============================================================================
#define ENUM(X, SEQ) \
struct X { \
enum Enum {BOOST_PP_SEQ_ENUM(SEQ)}; \
static const std::array array_of_strings() { \
return {{BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(STRINGIZE, 0, SEQ))}}; \
} \
static std::string to_string(Enum e) { \
auto a = array_of_strings(); \
return a[static_cast(e)]; \
} \
}
For std::string
to enum
conversion we would have to make a linear search over the array and cast the array index to enum
.
Try it here with usage examples: http://coliru.stacked-crooked.com/a/e4212f93bee65076
Edit: Reworked my solution so the custom Enum can be used inside a class.