Advertisement
hnOsmium0001

Untitled

Dec 4th, 2020
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <functional>
  4. #include <optional>
  5.  
  6. class OptionNone
  7. {
  8. };
  9.  
  10. template <class T>
  11. class Option
  12. {
  13. // TODO
  14. };
  15.  
  16. template <class T>
  17. class Option<T&>
  18. {
  19. private:
  20. T* ptr;
  21.  
  22. public:
  23. Option(T& ref)
  24. : ptr{ &ref }
  25. {
  26. }
  27.  
  28. Option(T* ptr)
  29. : ptr{ ptr }
  30. {
  31. }
  32.  
  33. Option()
  34. : ptr{ nullptr }
  35. {
  36. }
  37.  
  38. Option(const Option& that) = default;
  39. Option& operator=(const Option& that) = default;
  40. Option(Option&& that) = default;
  41. Option& operator=(Option&& that) = default;
  42.  
  43. Option& operator=(const OptionNone&)
  44. {
  45. ptr = nullptr;
  46. return *this;
  47. }
  48.  
  49. bool HasValue() const
  50. {
  51. return ptr;
  52. }
  53.  
  54. T& Get()
  55. {
  56. return *ptr;
  57. }
  58.  
  59. T& operator||(T& otherOption)
  60. {
  61. if (HasValue()) {
  62. return *ptr;
  63. } else {
  64. return otherOption;
  65. }
  66. }
  67.  
  68. T& operator||(std::function<T()> computeOption)
  69. {
  70. if (HasValue()) {
  71. return *ptr;
  72. } else {
  73. return computeOption();
  74. }
  75. }
  76. };
  77.  
  78. template <class T>
  79. static Option<T&> Some(T& ref)
  80. {
  81. return Option<T&>{ ref };
  82. }
  83.  
  84. template <class T>
  85. static Option<T&> None()
  86. {
  87. return Option<T&>{};
  88. }
  89.  
  90. static OptionNone None()
  91. {
  92. return OptionNone();
  93. }
  94.  
  95. void f() {
  96. int a = 1;
  97. int b = 32;
  98.  
  99. Option<int&> foo;
  100. foo = None();
  101. qInfo(foo.HasValue());
  102. qInfo(foo || a);
  103. qInfo(foo || [&]() { return b; });
  104. foo = Some(a);
  105. qInfo(foo.HasValue());
  106. }
  107.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement