From 90fc7638aee23270fe005f86dd1b492d67015c13 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Tue, 20 Apr 2021 18:11:45 +0300 Subject: [PATCH] Add equality comparison for Variant Besides value comparison, it's also possible to check if two Variant objects have the same type. --- source/core/meta.h | 12 ++++++++++++ source/core/variant.h | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/source/core/meta.h b/source/core/meta.h index 8015f42..6998c5d 100644 --- a/source/core/meta.h +++ b/source/core/meta.h @@ -58,6 +58,18 @@ struct Sfinae }; }; + +struct CheckEqualityComparable: Sfinae +{ + static int &v; + template + static Yes f(int (*)[sizeof(reinterpret_cast(v)==reinterpret_cast(v))]); + using Sfinae::f; +}; + +template +struct IsEqualityComparable: Sfinae::Evaluate { }; + } // namespace Msp #endif diff --git a/source/core/variant.h b/source/core/variant.h index 515350d..2dd9732 100644 --- a/source/core/variant.h +++ b/source/core/variant.h @@ -24,6 +24,8 @@ private: virtual const std::type_info &type_id() const = 0; virtual StoreBase *clone() const = 0; + virtual bool type_equals(const StoreBase &) const = 0; + virtual bool value_equals(const StoreBase &) const = 0; }; template @@ -35,6 +37,16 @@ private: virtual const std::type_info &type_id() const { return typeid(T); } virtual StoreBase *clone() const { return new Store(data); } + virtual bool type_equals(const StoreBase &s) const { return dynamic_cast *>(&s); } + virtual bool value_equals(const StoreBase &s) const { return value_equals_(s); } + + template + typename EnableIf::value, bool>::Yes value_equals_(const StoreBase &s) const + { const Store *t = dynamic_cast *>(&s); return (t && t->data==data); } + + template + typename EnableIf::value, bool>::No value_equals_(const StoreBase &) const + { return false; } }; StoreBase *store; @@ -91,6 +103,15 @@ public: return dynamic_cast::Type> *>(store)!=0; } + bool check_same_type(const Variant &v) const + { return store && v.store && store->type_equals(*v.store); } + + bool operator==(const Variant &v) const + { return store && v.store && store->value_equals(*v.store); } + + bool operator!=(const Variant &v) const + { return !(operator==(v)); } + template operator T() const { return value(); } -- 2.45.2