]> git.tdb.fi Git - libs/core.git/blob - source/core/variant.h
Avoid an extra copy by making Variant::Store's c'tor take a const ref
[libs/core.git] / source / core / variant.h
1 #ifndef MSP_CORE_VARIANT_H_
2 #define MSP_CORE_VARIANT_H_
3
4 #include <stdexcept>
5 #include <typeinfo>
6 #include "meta.h"
7
8 namespace Msp {
9
10 class type_mismatch: public std::runtime_error
11 {
12 public:
13         type_mismatch(const std::type_info &, const std::type_info &);
14         ~type_mismatch() throw() { }
15 };
16
17
18 class Variant
19 {
20 private:
21         struct StoreBase
22         {
23                 virtual ~StoreBase() { }
24
25                 virtual const std::type_info &type_id() const = 0;
26                 virtual StoreBase *clone() const = 0;
27         };
28
29         template<typename T>
30         struct Store: public StoreBase
31         {
32                 T data;
33
34                 Store(const T &d): data(d) { }
35
36                 virtual const std::type_info &type_id() const { return typeid(T); }
37                 virtual StoreBase *clone() const { return new Store<T>(data); }
38         };
39
40         StoreBase *store;
41
42 public:
43         Variant(): store(0) { }
44         template<typename T>
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; }
48
49         template<typename T>
50         Variant &operator=(const T &v)
51         {
52                 delete store;
53                 store = new Store<typename RemoveConst<T>::Type>(v);
54                 return *this;
55         }
56
57         Variant &operator=(const Variant &v)
58         {
59                 delete store;
60                 store = (v.store ? v.store->clone() : 0);
61                 return *this;
62         }
63
64 private:
65         template<typename T>
66         Store<typename RemoveConst<T>::Type> *get_typed_store() const
67         {
68                 typedef typename RemoveConst<T>::Type NCT;
69                 Store<NCT> *s = dynamic_cast<Store<NCT> *>(store);
70                 if(!s)
71                         throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void)));
72                 return s;
73         }
74
75 public:
76         template<typename T>
77         T &value()
78         {
79                 return get_typed_store<T>()->data;
80         }
81
82         template<typename T>
83         const T &value() const
84         {
85                 return get_typed_store<T>()->data;
86         }
87
88         template<typename T>
89         bool check_type() const
90         {
91                 return dynamic_cast<Store<typename RemoveConst<T>::Type> *>(store)!=0;
92         }
93
94         template<typename T>
95         operator T() const
96         { return value<T>(); }
97 };
98
99 } // namespace Msp
100
101 #endif