[ox/std] Make Optional more like std::optional

This commit is contained in:
Gary Talent 2023-02-19 01:40:29 -06:00
parent 2e051f947d
commit edd21017d3

View File

@ -51,14 +51,20 @@ class Optional {
} }
} }
template<typename U = T> constexpr T &value() & noexcept {
constexpr U *get() noexcept { return *m_ptr;
return m_ptr;
} }
template<typename U = T> constexpr const T &value() const & noexcept {
constexpr const U *get() const noexcept { return *m_ptr;
return m_ptr; }
constexpr T &&value() && noexcept {
return *m_ptr;
}
constexpr const T &&value() const && noexcept {
return *m_ptr;
} }
constexpr T &operator*() & noexcept { constexpr T &operator*() & noexcept {
@ -117,6 +123,7 @@ class Optional {
template<class... Args> template<class... Args>
constexpr T &emplace(Args &&...args) { constexpr T &emplace(Args &&...args) {
reset();
if (std::is_constant_evaluated()) { if (std::is_constant_evaluated()) {
m_ptr = new T(ox::forward<Args>(args)...); m_ptr = new T(ox::forward<Args>(args)...);
} else { } else {
@ -128,6 +135,7 @@ class Optional {
template<typename U, class... Args> template<typename U, class... Args>
constexpr T &emplace_subclass(Args &&...args) { constexpr T &emplace_subclass(Args &&...args) {
static_assert(sizeof(U) <= buffSize, "Subclass is too large for this Optional"); static_assert(sizeof(U) <= buffSize, "Subclass is too large for this Optional");
reset();
if (std::is_constant_evaluated()) { if (std::is_constant_evaluated()) {
m_ptr = new U(ox::forward<Args>(args)...); m_ptr = new U(ox::forward<Args>(args)...);
} else { } else {
@ -148,8 +156,8 @@ class Optional {
constexpr void reset() noexcept { constexpr void reset() noexcept {
if (std::is_constant_evaluated()) { if (std::is_constant_evaluated()) {
ox::safeDelete(m_ptr); ox::safeDelete(m_ptr);
} else { } else if (has_value()) {
get()->~T(); value().~T();
} }
m_ptr = nullptr; m_ptr = nullptr;
} }