Maybe.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #pragma once
  2. #include <functional>
  3. #include "Betriebssystem.h"
  4. namespace Framework
  5. {
  6. template<typename T> class Maybe
  7. {
  8. private:
  9. bool set;
  10. T value;
  11. Maybe()
  12. {
  13. set = 0;
  14. }
  15. Maybe(T value)
  16. : set(1),
  17. value(value){};
  18. public:
  19. static Maybe<T> of(T value)
  20. {
  21. return Maybe(value);
  22. }
  23. static Maybe<T> empty()
  24. {
  25. return Maybe();
  26. }
  27. bool isEmpty() const
  28. {
  29. return !set;
  30. }
  31. bool isPresent() const
  32. {
  33. return set;
  34. }
  35. operator T() const
  36. {
  37. assert(set);
  38. return value;
  39. }
  40. void ifPresent(std::function<T> action)
  41. {
  42. if (set) action(value);
  43. }
  44. void ifNotPresent(std::function<T> action)
  45. {
  46. if (!set) action(value);
  47. }
  48. template<typename R> Maybe<R> map(std::function<R(T)> action)
  49. {
  50. if (set)
  51. return Maybe<R>::of(action(value));
  52. else
  53. return Maybe<R>::empty();
  54. }
  55. template<typename R> Maybe<R> flatMap(std::function<Maybe<R>(T)> action)
  56. {
  57. if (set)
  58. return action(value);
  59. else
  60. return Maybe<R>::empty();
  61. }
  62. T orElse(T elseValue)
  63. {
  64. if (set)
  65. return value;
  66. else
  67. return elseValue;
  68. }
  69. T operator->()
  70. {
  71. assert(set);
  72. return value;
  73. }
  74. };
  75. } // namespace Framework