]> git.tdb.fi Git - libs/core.git/commitdiff
Improvements for empty variants
authorMikko Rasa <tdb@tdb.fi>
Sat, 9 Sep 2023 07:37:18 +0000 (10:37 +0300)
committerMikko Rasa <tdb@tdb.fi>
Sat, 9 Sep 2023 07:37:18 +0000 (10:37 +0300)
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
tests/variant.cpp

index 5cb1b931ca403eab55a0ef38e9be86b3afa3d0c5..b00f5616f7e83e2e39fe67889141153d539b4f60 100644 (file)
@@ -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<typename T>
@@ -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<typename T>
@@ -192,6 +193,16 @@ inline T &Variant::get()
                return **reinterpret_cast<T **>(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)
index 8ec89722197f4742e17164f2f251741c8a6ebd62..9bdfeda1857ee85718171d76f541e7beadc6ed0f 100644 (file)
@@ -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<type_mismatch>();
 }
@@ -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;