fork(10) download
  1.  
  2. template<typename E, E first, E head>
  3. void advanceEnum(E& v)
  4. {
  5. if(v == head)
  6. v = first;
  7. }
  8.  
  9. template<typename E, E first, E head, E next, E... tail>
  10. void advanceEnum(E& v)
  11. {
  12. if(v == head)
  13. v = next;
  14. else
  15. advanceEnum<E,first,next,tail...>(v);
  16. }
  17.  
  18. template<typename E, E first, E... values>
  19. struct EnumValues
  20. {
  21. static void advance(E& v)
  22. {
  23. advanceEnum<E, first, first, values...>(v);
  24. }
  25. };
  26.  
  27.  
  28.  
  29. /// Test enum
  30. enum class Fruit
  31. {
  32. apple,
  33. banana,
  34. orange,
  35. pineapple,
  36. lemon
  37. };
  38.  
  39.  
  40.  
  41. /// Scalable way, C++11-ish
  42. typedef EnumValues<Fruit,
  43. Fruit::apple,
  44. Fruit::banana,
  45. Fruit::orange,
  46. Fruit::pineapple,
  47. Fruit::lemon
  48. > Fruit_values11;
  49.  
  50. Fruit& operator++(Fruit& f)
  51. {
  52. Fruit_values11::advance(f);
  53. return f;
  54. }
  55.  
  56.  
  57. #include <iostream>
  58. std::ostream& operator<<(std::ostream& os, Fruit f)
  59. {
  60. switch(f)
  61. {
  62. case Fruit::apple: os << "Fruit::apple"; return os;
  63. case Fruit::banana: os << "Fruit::banana"; return os;
  64. case Fruit::orange: os << "Fruit::orange"; return os;
  65. case Fruit::pineapple: os << "Fruit::pineapple"; return os;
  66. case Fruit::lemon: os << "Fruit::lemon"; return os;
  67. }
  68. }
  69.  
  70. int main()
  71. {
  72. Fruit f = Fruit::banana;
  73. std::cout << "f = " << f << ";\n";
  74. std::cout << "++f = " << ++f << ";\n";
  75. std::cout << "++f = " << ++f << ";\n";
  76. std::cout << "++f = " << ++f << ";\n";
  77. std::cout << "++f = " << ++f << ";\n";
  78. std::cout << "++f = " << ++f << ";\n";
  79. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
f = Fruit::banana;
++f = Fruit::orange;
++f = Fruit::pineapple;
++f = Fruit::lemon;
++f = Fruit::apple;
++f = Fruit::banana;