SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // X-Macros used to keep an enumerated type aligned with
  2. // To- and From- String functions.
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <unordered_map>
  7.  
  8. // List the enumerated values
  9. #define COLOURS \
  10.     X(Red) \
  11.     X(Orange) \
  12.     X(Yellow) \
  13.     X(Green) \
  14.     X(Blue) \
  15.     X(Indigo) \
  16.     X(Violet)
  17.  
  18. enum Colour
  19. {
  20. #define X(x) x,
  21.     COLOURS
  22. #undef X
  23. };
  24.  
  25. std::string ToString(Colour c)
  26. {
  27.     switch(c)
  28.     {
  29. #define X(x) case x: return #x;
  30.         COLOURS
  31. #undef X
  32.     };
  33.     throw std::runtime_error("Unknown colour");
  34. }
  35.  
  36. Colour FromString(std::string const & s)
  37. {
  38.     static const std::unordered_map<std::string, Colour> lookup {
  39. #define X(x) {#x, x},
  40.         COLOURS
  41.     };
  42.     return lookup.at(s);
  43. }
  44.  
  45. int main()
  46. {
  47.     Colour colour = FromString("Orange");
  48.     std::cout << "My favourite colour is " << ToString(colour) << '\n';
  49.     return 0;
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top