optional.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #pragma once
  2. #include <stdexcept>
  3. template <typename T>
  4. class Optional
  5. {
  6. public:
  7. static Optional<T> of(T value)
  8. {
  9. Optional<T> result;
  10. result.exists = true;
  11. result.value = value;
  12. return result;
  13. }
  14. static Optional<T> _empty()
  15. {
  16. Optional<T> result;
  17. result.exists = false;
  18. return result;
  19. }
  20. /**
  21. * Check whether value exists or not
  22. **/
  23. bool absent() const
  24. {
  25. return !exists;
  26. }
  27. T orValue(T value) const
  28. {
  29. return exists ? this->value : value;
  30. }
  31. /**
  32. * return the element, or throw if absent
  33. * @throws std::logic_error
  34. * @return T value
  35. **/
  36. T get() const
  37. {
  38. if (!exists)
  39. throw std::logic_error("Optional does not contains value");
  40. return value;
  41. }
  42. T operator*() const
  43. {
  44. return get();
  45. }
  46. static Optional<T> empty;
  47. protected:
  48. T value;
  49. bool exists;
  50. private:
  51. Optional() {}
  52. };
  53. template <typename T> Optional<T> Optional<T>::empty = Optional<T>::_empty();