From 6d425182a28f7c87d785d154012fac84f410fa5a Mon Sep 17 00:00:00 2001 From: Bananymous Date: Tue, 18 Apr 2023 19:06:58 +0300 Subject: [PATCH] BAN: Variant::set now copy/move assigns when possible --- BAN/include/BAN/Variant.h | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/BAN/include/BAN/Variant.h b/BAN/include/BAN/Variant.h index ba410e2888..423342a01a 100644 --- a/BAN/include/BAN/Variant.h +++ b/BAN/include/BAN/Variant.h @@ -98,9 +98,7 @@ namespace BAN static constexpr size_t invalid_index() { return sizeof...(Ts); } public: - Variant() - : m_index(invalid_index()) - { } + Variant() = default; Variant(Variant&& other) : m_index(other.m_index) @@ -168,14 +166,14 @@ namespace BAN template Variant& operator=(T&& value) requires (can_have()) { - set(move(value)); + *this = Variant(move(value)); return *this; } template Variant& operator=(const T& value) requires (can_have()) { - set(value); + *this = Variant(value); return *this; } @@ -188,31 +186,41 @@ namespace BAN template void set(T&& value) requires (can_have()) { - clear(); - m_index = detail::index(); - new (m_storage) T(move(value)); + if (has()) + get() = move(value); + else + { + clear(); + m_index = detail::index(); + new (m_storage) T(move(value)); + } } template void set(const T& value) requires (can_have()) { - clear(); - m_index = detail::index(); - new (m_storage) T(value); + if (has()) + get() = value; + else + { + clear(); + m_index = detail::index(); + new (m_storage) T(value); + } } template T& get() requires (can_have()) { ASSERT(has()); - return (T&)m_storage; + return *reinterpret_cast(m_storage); } template const T& get() const requires (can_have()) { ASSERT(has()); - return (const T&)m_storage; + return *reinterpret_cast(m_storage); } void clear()