33 static_assert(!std::is_reference<T>::value,
"Do not use a reference for T");
35 constexpr OptionalRef()
noexcept =
default;
36 constexpr OptionalRef(std::nullopt_t)
noexcept {}
37 constexpr OptionalRef(
const OptionalRef&)
noexcept =
default;
40 constexpr OptionalRef(T& other)
noexcept : data_(std::addressof(other)) {}
43 constexpr explicit OptionalRef(
const T&&) =
delete;
46 constexpr explicit OptionalRef(
const std::optional<U>& other)
noexcept : data_(GetPointer(other)) {}
49 constexpr explicit OptionalRef(std::optional<U>& other)
noexcept : data_(GetPointer(other)) {}
52 constexpr explicit OptionalRef(
const std::optional<U>&&)
noexcept {
53 static_assert(!
sizeof(U),
"Forming a reference to a temporary");
56 constexpr bool has_value()
const noexcept {
return !!data_; }
57 constexpr explicit operator
bool()
const noexcept {
return has_value(); }
59 constexpr T* operator->()
const {
64 constexpr T& operator*()
const {
69 constexpr T& value()
const {
71 throw std::bad_optional_access();
78 constexpr T value_or(U&& default_value)
const {
80 return std::forward<U>(default_value);
87 constexpr auto and_then(F&& function)
const -> std::remove_cvref_t<std::invoke_result_t<F, T&>> {
88 using Result = std::remove_cvref_t<std::invoke_result_t<F, T&>>;
90 meta::IsInstantiationOf<Result, std::optional> ||
meta::IsInstantiationOf<Result,
OptionalRef>,
91 "The function passed to and_then must return std::optional or utils::OptionalRef"
95 return std::invoke(std::forward<F>(function), *data_);
100 template <
typename F>
101 constexpr auto transform(F&& function)
const {
102 using Result = std::remove_cv_t<std::invoke_result_t<F, T&>>;
105 return std::optional<Result>{std::invoke(std::forward<F>(function), *data_)};
107 return std::optional<Result>{};
110 template <
typename F>
111 constexpr OptionalRef or_else(F&& function)
const {
112 using Result = std::remove_cvref_t<std::invoke_result_t<F>>;
115 "The function passed to or_else must return utils::OptionalRef<T>"
121 return std::invoke(std::forward<F>(function));
125 template <
class Optional>
126 static T* GetPointer(Optional& other)
noexcept {
127 using ValueType =
decltype(*other);
129 std::is_const<T>::value || !std::is_const<ValueType>::value,
130 "Attempt to initialize non-const T from a const optional value"
133 return other.has_value() ? std::addressof(*other) :
nullptr;
136 T*
const data_ =
nullptr;