c++ - How can I eliminate the boilerplate of this enum to string mapping code? -


i have following code not defines scoped enumeration, has corresponding mapping can use stringized version of enumerators directly iostream operator overloads.

enum class arbitrarynumbers {     one,     two,     three,     four,     5 };  namespace {     using bm_type = boost::bimap<arbitrarynumbers, std::string>;     bm_type const g_arbitrarynumbersmap = boost::assign::list_of<bm_type::relation>         (arbitrarynumbers::one, "one")         (arbitrarynumbers::two, "two")         (arbitrarynumbers::three, "three")         (arbitrarynumbers::four, "four")         (arbitrarynumbers::five, "five")         ; }  std::ostream& operator<< (std::ostream& os, arbitrarynumbers number) {     auto = g_arbitrarynumbersmap.left.find(status);     if (it != g_arbitrarynumbersmap.left.end())     {         os << it->second;     }     else     {         os.setstate(std::ios_base::failbit);     }      return os; }  std::istream& operator>> (std::istream& is, arbitrarynumbers& number) {     std::string number_string;     >> number_string;     auto = g_arbitrarynumbersmap.right.find(number_string);     if (it != g_arbitrarynumbersmap.right.end())     {         status = it->second;     }     else     {         is.setstate(std::ios_base::failbit);     }      return is; } 

i'd wrap in sort of reusable fashion. think best solution involve macros, ideally this:

begin_scoped_enum(arbitrarynumbers)     enumerator(one)     enumerator(two)     enumerator(three)     enumerator(four)     enumerator(five) end_scoped_enum() 

this mfc-like, immediate turn-off me. @ least easier on eyes. point eliminates boilerplate , less error prone since mapping doesn't need kept in sync additions or removals , enumeration itself.

is there way can accomplish boost.preprocessor, template trickery, or other useful mechanic?

i did find ideas online of hand-spun macros, want avoid. feel if have go macro approach boost.preprocessor able me, it's complex use , i'm not sure how use solve problem. of solutions found dated, , want see if answers different features introduced in stl , core language since between c++03 , c++14.

i'd write array:

std::string array[] = {"one", "two", "three"}; 

i guess issue same generating sin-tables automatically.


Comments