"demo_enum.h"

  1. #include "enum2string.h" 
  2.  
  3. //enum Type { 
  4. //  Foo, 
  5. //  Bar, 
  6. //  Team 
  7. //}; 
  8.  
  9. DEFINE_ENUM_WITH_STRING_CONVERSIONS(Type, (Foo)(Bar)(Team)) 

"enum2string.h"

 

  1. #include <boost/preprocessor.hpp> 
  2.  
  3. #define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE(r, data, elem)    \ 
  4.     case elem : return BOOST_PP_STRINGIZE(elem); 
  5.  
  6. #define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators)                \ 
  7.     enum name {                                                               \ 
  8.         BOOST_PP_SEQ_ENUM(enumerators)                                        \ 
  9.     };                                                                        \ 
  10.                                                                               \ 
  11.     inline char* ToString(name v)                                       \ 
  12.     {                                                                         \ 
  13.         switch (v)                                                            \ 
  14.         {                                                                     \ 
  15.             BOOST_PP_SEQ_FOR_EACH(                                            \ 
  16.                 X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE,          \ 
  17.                 name,                                                         \ 
  18.                 enumerators                                                   \ 
  19.             )                                                                 \ 
  20.             defaultreturn "[Unknown " BOOST_PP_STRINGIZE(name) "]";         \ 
  21.         }                                                                     \ 
  22.     } 

 

"main.cpp"

 

  1. #include "demo_enum.h" 
  2.  
  3. int main(int argc, char* argv[]) 
  4.     Type t = Team; 
  5.     char *p = ToString(t); 
  6.     char *p1 = ToString(Team); 
  7.  
  8.     return 0; 

Reference: 

http://stackoverflow.com/questions/5093460/how-to-convert-an-enum-type-variable-to-a-string

http://stackoverflow.com/questions/10175260/enum-to-string-return-the-enum-integer-value-if-invalid-not-found