aboutsummaryrefslogtreecommitdiff
path: root/option.h
diff options
context:
space:
mode:
authorJohannes Stoelp <johannes.stoelp@gmail.com>2024-10-07 22:03:56 +0200
committerJohannes Stoelp <johannes.stoelp@gmail.com>2024-10-07 22:03:56 +0200
commit3f62112e3a1b180a9b931d6f43b3cdc74e7ba3b9 (patch)
treea8201bf501f2c9690e51109d8be31c2fb4af7e4a /option.h
parentaf7a61a5464c266426a20e7dacf6c52bb80b28e9 (diff)
downloadcpp-utils-3f62112e3a1b180a9b931d6f43b3cdc74e7ba3b9.tar.gz
cpp-utils-3f62112e3a1b180a9b931d6f43b3cdc74e7ba3b9.zip
option: assignment operator + minor cleanupHEADmain
Diffstat (limited to 'option.h')
-rw-r--r--option.h37
1 files changed, 34 insertions, 3 deletions
diff --git a/option.h b/option.h
index 20104d7..cd12f88 100644
--- a/option.h
+++ b/option.h
@@ -29,7 +29,7 @@ struct option {
// -- CONSTRUCTOR - NONE -----------------------------------------------------
constexpr option() = default;
- constexpr option(none) : option() {}
+ constexpr option(none) noexcept : option() {}
// -- CONSTRUCTOR - VALUE ----------------------------------------------------
@@ -47,11 +47,40 @@ struct option {
}
}
- template <typename U = T>
- constexpr option(T&& val) : m_has_value{true} {
+ constexpr option(const T& val) : m_has_value{true} {
+ new (&m_value) T(val);
+ }
+
+ constexpr option(T&& val) noexcept : m_has_value{true} {
new (&m_value) T(std::move(val));
}
+ // -- ASSIGNMENT -------------------------------------------------------------
+
+ constexpr option& operator=(const option& op) {
+ if (this == &op) {
+ return *this;
+ }
+ reset();
+ if (op.has_value()) {
+ new (&m_value) T(op.value());
+ m_has_value = true;
+ }
+ return *this;
+ }
+
+ constexpr option& operator=(option&& op) noexcept {
+ if (this == &op) {
+ return *this;
+ }
+ reset();
+ if (op.has_value()) {
+ new (&m_value) T(std::move(op.take()));
+ m_has_value = true;
+ }
+ return *this;
+ }
+
// -- DESTRUCTOR -------------------------------------------------------------
~option() {
@@ -62,6 +91,8 @@ struct option {
template <typename... Params>
constexpr T& emplace(Params&&... params) {
+ static_assert(std::is_constructible<T, Params...>::value,
+ "T not constructible from Params...");
reset();
new (&m_value) T(std::forward<Params>(params)...);
m_has_value = true;