ccls/src/maybe.h

45 lines
1.2 KiB
C
Raw Normal View History

#pragma once
2018-03-31 03:16:33 +00:00
#include <optional>
#include <utility>
2018-03-31 03:16:33 +00:00
// Like std::optional, but the stored data is responsible for containing the empty
2018-02-11 21:49:44 +00:00
// state. T should define a function `bool T::HasValueForMaybe_()`.
template <typename T>
class Maybe {
T storage;
2018-02-22 07:34:32 +00:00
public:
constexpr Maybe() = default;
Maybe(const Maybe&) = default;
Maybe(std::nullopt_t) {}
Maybe(const T& x) : storage(x) {}
Maybe(T&& x) : storage(std::forward<T>(x)) {}
Maybe& operator=(const Maybe&) = default;
Maybe& operator=(const T& x) {
storage = x;
return *this;
}
2018-02-22 07:34:32 +00:00
const T* operator->() const { return &storage; }
T* operator->() { return &storage; }
const T& operator*() const { return storage; }
T& operator*() { return storage; }
2018-02-22 07:34:32 +00:00
bool HasValue() const { return storage.HasValueForMaybe_(); }
explicit operator bool() const { return HasValue(); }
2018-03-31 03:16:33 +00:00
operator std::optional<T>() const {
if (HasValue())
return storage;
2018-03-31 03:16:33 +00:00
return std::nullopt;
}
2018-03-31 03:16:33 +00:00
void operator=(std::optional<T>&& o) { storage = o ? *o : T(); }
// Does not test if has_value()
2018-02-22 07:34:32 +00:00
bool operator==(const Maybe& o) const { return storage == o.storage; }
bool operator!=(const Maybe& o) const { return !(*this == o); }
};