BAN: Implement Optional::value_or

This will return value specified in the argument if optional is not
storing any value.
This commit is contained in:
Bananymous 2024-07-12 11:22:10 +03:00
parent e905634343
commit 62003d96f3
1 changed files with 19 additions and 1 deletions

View File

@ -40,6 +40,8 @@ namespace BAN
constexpr T release_value(); constexpr T release_value();
constexpr T& value(); constexpr T& value();
constexpr const T& value() const; constexpr const T& value() const;
constexpr T& value_or(T&);
constexpr const T& value_or(const T&) const;
constexpr void clear(); constexpr void clear();
@ -112,7 +114,7 @@ namespace BAN
{ {
clear(); clear();
m_has_value = other.has_value(); m_has_value = other.has_value();
if (other.has_value) if (other.has_value())
new (m_storage) T(other.value()); new (m_storage) T(other.value());
return *this; return *this;
} }
@ -185,6 +187,22 @@ namespace BAN
return (const T&)m_storage; return (const T&)m_storage;
} }
template<typename T>
constexpr T& Optional<T>::value_or(T& empty)
{
if (!has_value())
return empty;
return (T&)m_storage;
}
template<typename T>
constexpr const T& Optional<T>::value_or(const T& empty) const
{
if (!has_value())
return empty;
return (const T&)m_storage;
}
template<typename T> template<typename T>
constexpr void Optional<T>::clear() constexpr void Optional<T>::clear()
{ {