1 #ifndef MSP_CORE_VARIANT_H_
2 #define MSP_CORE_VARIANT_H_
11 class type_mismatch: public std::runtime_error
14 type_mismatch(const std::type_info &, const std::type_info &);
15 virtual ~type_mismatch() throw() = default;
24 virtual ~StoreBase() { }
26 virtual const std::type_info &type_id() const = 0;
27 virtual StoreBase *clone() const = 0;
28 virtual bool type_equals(const StoreBase &) const = 0;
29 virtual bool value_equals(const StoreBase &) const = 0;
33 struct Store: public StoreBase
37 Store(const T &d): data(d) { }
39 virtual const std::type_info &type_id() const { return typeid(T); }
40 virtual StoreBase *clone() const { return new Store<T>(data); }
41 virtual bool type_equals(const StoreBase &s) const { return dynamic_cast<const Store<T> *>(&s); }
42 virtual bool value_equals(const StoreBase &s) const { return value_equals_<T>(s); }
45 typename std::enable_if<IsEqualityComparable<U>::value, bool>::type value_equals_(const StoreBase &s) const
46 { const Store<T> *t = dynamic_cast<const Store<T> *>(&s); return (t && t->data==data); }
49 typename std::enable_if<!IsEqualityComparable<U>::value, bool>::type value_equals_(const StoreBase &) const
58 Variant(const T &v): store(new Store<typename std::remove_cv<T>::type>(v)) { }
59 Variant(const Variant &v): store(v.store ? v.store->clone() : 0) { }
60 ~Variant() { delete store; }
63 Variant &operator=(const T &v)
66 store = new Store<typename std::remove_cv<T>::type>(v);
70 Variant &operator=(const Variant &v)
73 store = (v.store ? v.store->clone() : 0);
79 Store<typename std::remove_cv<T>::type> *get_typed_store() const
81 typedef typename std::remove_cv<T>::type NCT;
82 Store<NCT> *s = dynamic_cast<Store<NCT> *>(store);
84 throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void)));
92 return get_typed_store<T>()->data;
96 const T &value() const
98 return get_typed_store<T>()->data;
102 bool check_type() const
104 return dynamic_cast<Store<typename std::remove_cv<T>::type> *>(store)!=0;
107 bool check_same_type(const Variant &v) const
108 { return store && v.store && store->type_equals(*v.store); }
110 bool operator==(const Variant &v) const
111 { return store && v.store && store->value_equals(*v.store); }
113 bool operator!=(const Variant &v) const
114 { return !(operator==(v)); }
118 { return value<T>(); }