From 857cb78e1568ccd55562f9602c247882dfa7bb0b Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 9 Sep 2023 10:37:18 +0300 Subject: [PATCH] Improvements for empty variants There's now a function to check if an empty variant holds a value, and two empty variants will compare as equal. --- source/core/variant.h | 13 ++++++++++++- tests/variant.cpp | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/source/core/variant.h b/source/core/variant.h index 5cb1b93..b00f561 100644 --- a/source/core/variant.h +++ b/source/core/variant.h @@ -52,6 +52,7 @@ public: Variant &operator=(Variant &&v) { if(&v!=this) move_from(std::move(v)); return *this; } void clear(); + bool has_value() const { return funcs; } private: template @@ -80,7 +81,7 @@ public: DEPRECATED bool check_same_type(const Variant &v) const { return has_same_type(v); } - bool operator==(const Variant &v) const { return (has_same_type(v) && funcs->compare(storage, v.storage)); } + bool operator==(const Variant &v) const; bool operator!=(const Variant &v) const { return !(operator==(v)); } template @@ -192,6 +193,16 @@ inline T &Variant::get() return **reinterpret_cast(storage); } +inline bool Variant::operator==(const Variant &other) const +{ + if(!funcs && !other.funcs) + return true; + else if(has_same_type(other)) + return funcs->compare(storage, other.storage); + else + return false; +} + inline bool Variant::type_equals(const Functions *funcs1, const Functions *funcs2) { if(!funcs1 || !funcs2) diff --git a/tests/variant.cpp b/tests/variant.cpp index 8ec8972..9bdfeda 100644 --- a/tests/variant.cpp +++ b/tests/variant.cpp @@ -18,6 +18,7 @@ private: void ref_into(); void copying(); void destruction(); + void compare(); void types(); void mismatch(); }; @@ -41,6 +42,7 @@ VariantTests::VariantTests() add(&VariantTests::ref_into, "Reference into"); add(&VariantTests::copying, "Copying"); add(&VariantTests::destruction, "Destruction"); + add(&VariantTests::compare, "Comparisons"); add(&VariantTests::types, "Type checks"); add(&VariantTests::mismatch, "Mismatch").expect_throw(); } @@ -96,6 +98,19 @@ void VariantTests::destruction() EXPECT_EQUAL(count, 0); } +void VariantTests::compare() +{ + Variant var = 1; + Variant var2 = 1; + Variant var3 = 4.2f; + Variant var4; + Variant var5; + EXPECT(var==var2); + EXPECT(var!=var3); + EXPECT(var!=var4); + EXPECT(var4==var5); +} + void VariantTests::types() { Variant var = 42U; -- 2.45.2