Either.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #pragma once
  2. #include <functional>
  3. #include "OperatingSystem.h"
  4. namespace Framework
  5. {
  6. template<typename A, typename B> class Either
  7. {
  8. private:
  9. union
  10. {
  11. A aValue;
  12. B bValue;
  13. };
  14. bool a;
  15. public:
  16. Either(const Either<A, B>& b)
  17. {
  18. a = b.isA();
  19. if (a)
  20. aValue = (A)b;
  21. else
  22. bValue = (B)b;
  23. }
  24. Either(A a)
  25. {
  26. aValue = a;
  27. this->a = 1;
  28. }
  29. Either(B b)
  30. {
  31. bValue = b;
  32. a = 0;
  33. }
  34. bool isA() const
  35. {
  36. return a;
  37. }
  38. bool isB() const
  39. {
  40. return !a;
  41. }
  42. A getA() const
  43. {
  44. assert(a);
  45. return aValue;
  46. }
  47. B getB() const
  48. {
  49. assert(!a);
  50. return bValue;
  51. }
  52. void doIfA(std::function<A> action)
  53. {
  54. if (a) action(aValue);
  55. }
  56. void doIfB(std::function<B> action)
  57. {
  58. if (!a) action(bValue);
  59. }
  60. operator A() const
  61. {
  62. assert(a);
  63. return aValue;
  64. }
  65. operator B() const
  66. {
  67. assert(!a);
  68. return bValue;
  69. }
  70. Either<A, B>& operator=(const Either<A, B>& b)
  71. {
  72. a = b.isA();
  73. if (a)
  74. aValue = (A)b;
  75. else
  76. bValue = (B)b;
  77. return *this;
  78. }
  79. Either<A, B>& operator=(const A& a)
  80. {
  81. a = 1;
  82. aValue = a;
  83. return *this;
  84. }
  85. Either<A, B>& operator=(const B& b)
  86. {
  87. a = 0;
  88. bValue = b;
  89. return *this;
  90. }
  91. };
  92. } // namespace Framework