3 This file is part of libmspcore
4 Copyright © 2008 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
8 #ifndef MSP_CORE_VARIANT_H_
9 #define MSP_CORE_VARIANT_H_
17 class type_mismatch: public std::runtime_error
20 type_mismatch(const std::type_info &, const std::type_info &);
21 ~type_mismatch() throw() { }
30 virtual ~StoreBase() { }
32 virtual const std::type_info &type_id() const = 0;
33 virtual StoreBase *clone() const = 0;
37 struct Store: public StoreBase
41 Store(T d): data(d) { }
43 virtual const std::type_info &type_id() const { return typeid(T); }
44 virtual StoreBase *clone() const { return new Store<T>(data); }
50 Variant(): store(0) { }
52 Variant(const T &v): store(new Store<typename RemoveConst<T>::Type>(v)) { }
53 Variant(const Variant &v): store(v.store ? v.store->clone() : 0) { }
54 ~Variant() { delete store; }
57 Variant &operator=(const T &v)
60 store = new Store<typename RemoveConst<T>::Type>(v);
64 Variant &operator=(const Variant &v)
67 store = (v.store ? v.store->clone() : 0);
74 typedef typename RemoveConst<T>::Type NCT;
75 Store<NCT> *s = dynamic_cast<Store<NCT> *>(store);
77 throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void)));
82 bool check_type() const
84 return dynamic_cast<Store<typename RemoveConst<T>::Type> *>(store)!=0;
89 { return value<T>(); }