optional: minor improvements

This change makes minor improvements to the optional class used with
pre-C++17 compilers.

- adds operator== and operator!=
- adds various missing noexcept (but not constexpr) decorations
- defines operator bool in terms of has_value

Note that some constexpr decorations would require C++17 anyway.

	* include/abg-cxx-compat.h (optional): Add operator== and
	operator!=. Add noexcept decorations. Tweak operator bool.

Reviewed-by: Matthias Maennich <maennich@google.com>
Signed-off-by: Giuliano Procida <gprocida@google.com>
This commit is contained in:
Giuliano Procida 2022-06-13 15:25:31 +01:00 committed by Dodji Seketeli
parent d15c30e319
commit ce7bd9f595

View File

@ -45,7 +45,7 @@ public:
optional(const T& value) : has_value_(true), value_(value) {} optional(const T& value) : has_value_(true), value_(value) {}
bool bool
has_value() const has_value() const noexcept
{ {
return has_value_; return has_value_;
} }
@ -67,19 +67,19 @@ public:
} }
const T& const T&
operator*() const operator*() const& noexcept
{ return value_; } { return value_; }
T& T&
operator*() operator*() & noexcept
{ return value_; } { return value_; }
const T* const T*
operator->() const operator->() const noexcept
{ return &value_; } { return &value_; }
T* T*
operator->() operator->() noexcept
{ return &value_; } { return &value_; }
optional& optional&
@ -90,9 +90,27 @@ public:
return *this; return *this;
} }
explicit operator bool() const { return has_value_; } explicit operator bool() const noexcept { return has_value(); }
}; };
template <typename T, typename U>
bool
operator==(const optional<T>& lhs, const optional<U>& rhs)
{
if (!lhs.has_value() && !rhs.has_value())
return true;
if (!lhs.has_value() || !rhs.has_value())
return false;
return lhs.value() == rhs.value();
}
template <typename T, typename U>
bool
operator!=(const optional<T>& lhs, const optional<U>& rhs)
{
return !(lhs == rhs);
}
#endif #endif
} }