1 #ifndef MSP_CORE_VARIANT_H_
2 #define MSP_CORE_VARIANT_H_
10 class type_mismatch: public std::runtime_error
13 type_mismatch(const std::type_info &, const std::type_info &);
14 ~type_mismatch() throw() { }
23 virtual ~StoreBase() { }
25 virtual const std::type_info &type_id() const = 0;
26 virtual StoreBase *clone() const = 0;
30 struct Store: public StoreBase
34 Store(const T &d): data(d) { }
36 virtual const std::type_info &type_id() const { return typeid(T); }
37 virtual StoreBase *clone() const { return new Store<T>(data); }
43 Variant(): store(0) { }
45 Variant(const T &v): store(new Store<typename RemoveConst<T>::Type>(v)) { }
46 Variant(const Variant &v): store(v.store ? v.store->clone() : 0) { }
47 ~Variant() { delete store; }
50 Variant &operator=(const T &v)
53 store = new Store<typename RemoveConst<T>::Type>(v);
57 Variant &operator=(const Variant &v)
60 store = (v.store ? v.store->clone() : 0);
66 Store<typename RemoveConst<T>::Type> *get_typed_store() const
68 typedef typename RemoveConst<T>::Type NCT;
69 Store<NCT> *s = dynamic_cast<Store<NCT> *>(store);
71 throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void)));
79 return get_typed_store<T>()->data;
83 const T &value() const
85 return get_typed_store<T>()->data;
89 bool check_type() const
91 return dynamic_cast<Store<typename RemoveConst<T>::Type> *>(store)!=0;
96 { return value<T>(); }