1 #ifndef cbe__util__Optional_h__
2 #define cbe__util__Optional_h__
21 bool hasValue_ =
false;
23 using RawMemory =
typename std::aligned_storage<
sizeof(T),
alignof(T)>::type;
39 new (payLoad) T{
value};
45 Optional(T&&
value) noexcept(std::is_nothrow_move_constructible<T>::value)
48 new (payLoad) T{std::move(
value)};
57 new (payLoad) T{rh.value_cast()};
65 : hasValue_{rh.hasValue_} {
67 new (payLoad) T{std::move(rh.value_cast())};
103 using std::runtime_error::runtime_error;
112 throw BadAccess{
"Value access of an empty Optional"};
132 const T& operator*()
const {
135 const T* operator->()
const {
143 bool hasValue() const noexcept {
return hasValue_; }
172 explicit operator bool() const noexcept {
return hasValue(); }
190 if (
this != &other) {
191 if (!other.hasValue_) {
194 new (&other)
Optional{std::move(value_cast())};
201 new (
this)
Optional{std::move(other.value_cast())};
205 std::swap(value_cast(), other.value_cast());
217 template <
typename... ArgTs>
220 new (payLoad) T(std::forward<ArgTs>(args)...);
224 inline T& value_cast() noexcept {
226 return *
reinterpret_cast<T*
>(payLoad);
228 inline const T& value_cast() const noexcept {
229 return const_cast<Optional*
>(
this)->value_cast();;
Thrown by value() method when accessing an object that does not contain a value.
Definition: Optional.h:102
Class template Optional manages an optional contained value - i.e., a value that is either present or...
Definition: Optional.h:20
Optional(const Optional &rh)
Copy ctor.
Definition: Optional.h:55
const T & value() const
Value access const method.
Definition: Optional.h:127
Optional(const T &value)
Copy value ctor.
Definition: Optional.h:36
void emplace(ArgTs &&... args)
Constructs the contained value in-place. If *this already contains a value before the call,...
Definition: Optional.h:218
Optional & operator=(const Optional &rh)
Copy assignment operator.
Definition: Optional.h:75
Optional & operator=(Optional &&rh) noexcept
Move assignment operator.
Definition: Optional.h:86
Optional()=default
Creates an empty Optional, i.e., no value present.
T & value()
Value access non-const method.
Definition: Optional.h:110
void reset()
Invalidates possible contained value. The contained value will be destructed.
Definition: Optional.h:179
bool hasValue() const noexcept
Checks whether a value is present.
Definition: Optional.h:143
Optional(T &&value) noexcept(std::is_nothrow_move_constructible< T >::value)
Move value ctor.
Definition: Optional.h:45
void swap(Optional &other) noexcept
Swaps the contents with those of other.
Definition: Optional.h:189
Optional(Optional &&rh) noexcept(std::is_nothrow_move_constructible< T >::value)
Move ctor.
Definition: Optional.h:64
Root namespace for the CloudBackend SDK API.
Definition: Account.h:22