pikaOptional.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include <type_traits>
  3. #include <pikaConfig.h>
  4. #include <logs/assert.h>
  5. namespace pika
  6. {
  7. struct Nullopt_t
  8. {
  9. constexpr explicit Nullopt_t() {};
  10. };
  11. inline constexpr Nullopt_t nullopt{Nullopt_t{}};
  12. template<class T>
  13. struct Optional
  14. {
  15. Optional() {};
  16. Optional(T &other)
  17. {
  18. data = other;
  19. hasValue_ = true;
  20. }
  21. Optional(T &&other)
  22. {
  23. data = std::forward<T>(other);
  24. hasValue_ = true;
  25. }
  26. Optional(const Nullopt_t &nullopt)
  27. {
  28. data = {};
  29. hasValue_ = false;
  30. }
  31. Optional &operator=(const Optional &other)
  32. {
  33. data = other.data;
  34. hasValue_ = true;
  35. return *this;
  36. }
  37. Optional &operator=(const T &other)
  38. {
  39. data = other;
  40. hasValue_ = true;
  41. return *this;
  42. }
  43. Optional &operator=(const Nullopt_t &nullopt)
  44. {
  45. data = {};
  46. hasValue_ = false;
  47. return *this;
  48. }
  49. T &value()
  50. {
  51. #if !PIKA_REMOVE_OPTIONAL_NOVALUE_CHECKS_IN_PRODUCTION || !PIKA_PRODUCTION
  52. PIKA_PERMA_ASSERT(hasValue_, "Invalid value acces in optional")
  53. #endif
  54. return data;
  55. }
  56. operator T& () const
  57. {
  58. return value();
  59. }
  60. bool hasValue() { return hasValue_; }
  61. private:
  62. bool hasValue_ = false;
  63. T data = {};
  64. };
  65. }