enh(Nullable, Optional): reimplement using std::optional (#4502)

This commit is contained in:
Matej Kenda
2024-09-18 17:06:54 +02:00
parent 03c35cff93
commit e55bb7032d
4 changed files with 63 additions and 102 deletions

View File

@@ -20,7 +20,7 @@
#include "Poco/Foundation.h"
#include "Poco/Exception.h"
#include <algorithm>
#include <optional>
namespace Poco {
@@ -53,40 +53,33 @@ class Optional
/// nillable == true.
{
public:
Optional():
Optional()
/// Creates an empty Optional.
_value(),
_isSpecified(false)
{
}
Optional(const C& value):
/// Creates a Optional with the given value.
_value(value),
_isSpecified(true)
_optional(value)
{
}
Optional(C&& value):
/// Creates a Optional by moving the given value.
_value(std::forward<C>(value)),
_isSpecified(true)
_optional(std::forward<C>(value))
{
}
Optional(const Optional& other):
/// Creates a Optional by copying another one.
_value(other._value),
_isSpecified(other._isSpecified)
_optional(other._optional)
{
}
Optional(Optional&& other) noexcept:
/// Creates a Optional by moving another one.
_value(std::move(other._value)),
_isSpecified(other._isSpecified)
_optional(std::move(other._optional))
{
other._isSpecified = false;
}
~Optional()
@@ -97,16 +90,14 @@ public:
Optional& assign(const C& value)
/// Assigns a value to the Optional.
{
_value = value;
_isSpecified = true;
_optional.emplace(value);
return *this;
}
Optional& assign(C&& value)
/// Moves a value into the Optional.
{
_value = std::move(value);
_isSpecified = true;
_optional.emplace(std::move(value));
return *this;
}
@@ -135,17 +126,14 @@ public:
Optional& operator = (Optional&& other) noexcept
{
_value = std::move(other._value);
_isSpecified = other._isSpecified;
other._isSpecified = false;
_optional = std::move(other._optional);
return *this;
}
void swap(Optional& other) noexcept
{
using std::swap;
swap(_value, other._value);
swap(_isSpecified, other._isSpecified);
swap(_optional, other._optional);
}
const C& value() const
@@ -153,10 +141,10 @@ public:
///
/// Throws a Poco::NullValueException if the value has not been specified.
{
if (_isSpecified)
return _value;
else
throw Poco::NullValueException();
if (_optional.has_value())
return _optional.value();
throw Poco::NullValueException();
}
const C& value(const C& deflt) const
@@ -164,24 +152,27 @@ public:
/// given default value if the Optional's
/// value has not been specified.
{
return _isSpecified ? _value : deflt;
if (_optional.has_value())
return _optional.value();
return deflt;
}
bool isSpecified() const
/// Returns true iff the Optional's value has been specified.
{
return _isSpecified;
return _optional.has_value();
}
void clear()
/// Clears the Optional.
{
_isSpecified = false;
_optional.reset();
}
private:
C _value;
bool _isSpecified;
std::optional<C> _optional;
};