fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <map>
  5.  
  6.  
  7. // http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c
  8. std::vector<std::string> split(const std::string &text, char sep) {
  9. std::vector<std::string> tokens;
  10. size_t start = 0, end = 0;
  11. while ((end = text.find(sep, start)) != std::string::npos) {
  12. tokens.push_back(text.substr(start, end - start));
  13. start = end + 1;
  14. }
  15. tokens.push_back(text.substr(start));
  16. return tokens;
  17. }
  18.  
  19. std::vector<std::string> parse(const char* args)
  20. {
  21. return split(args, ',');
  22. }
  23.  
  24. std::vector<std::string> parse(const char* args);
  25.  
  26. template<typename T, typename ...Ts>
  27. std::map<T, std::string> make_map(const char* text, Ts... args)
  28. {
  29. std::vector<T> keys{args...};
  30. std::vector<std::string> vals = parse(text);
  31. auto k = keys.cbegin();
  32. auto v = vals.cbegin();
  33. std::map<T, std::string> r;
  34. for (; k != keys.cend(); k++, v++) {
  35. r.emplace(*k, *v);
  36. }
  37. return r;
  38.  
  39. }
  40.  
  41. #define ENUM(name, ...) \
  42. enum name \
  43. { \
  44.   __VA_ARGS__ \
  45. }; \
  46. static std::string to_string(const name v) { \
  47.   static std::map<name, std::string> m {make_map<name>(#__VA_ARGS__, __VA_ARGS__)};\
  48.   return m.at(v); \
  49. }
  50.  
  51.  
  52. ENUM(Color, Red,Green,Blue)
  53. namespace ns {
  54. ENUM(Alignment, Left,Right)
  55. }
  56.  
  57. class X
  58. {
  59. public:
  60. ENUM(Y,A,B,C)
  61. };
  62.  
  63.  
  64. int main(int , char**)
  65. {
  66. std::cout << to_string(Red) << to_string(Blue);
  67. std::cout << to_string(ns::Left) << to_string(ns::Right);
  68. std::cout << X::to_string(X::A) << X::to_string(X::B);
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
RedBlueLeftRightAB