]> git.tdb.fi Git - libs/core.git/blob - source/core/variant.h
Handle constness in Variant
[libs/core.git] / source / core / variant.h
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_CORE_VARIANT_H_
9 #define MSP_CORE_VARIANT_H_
10
11 #include "except.h"
12 #include "meta.h"
13
14 namespace Msp {
15
16 class Variant
17 {
18 private:
19         struct StoreBase
20         {
21                 virtual ~StoreBase() { }
22         };
23
24         template<typename T>
25         struct Store: public StoreBase
26         {
27                 T data;
28
29                 Store(T d): data(d) { }
30         };
31
32         StoreBase *store;
33
34 public:
35         Variant(): store(0) { }
36         template<typename T>
37         Variant(const T &v): store(new Store<typename RemoveConst<T>::Type>(v)) { }
38         ~Variant() { delete store; }
39
40         template<typename T>
41         Variant &operator=(const T &v)
42         {
43                 delete store;
44                 store=new Store<typename RemoveConst<T>::Type>(v);
45                 return *this;
46         }
47
48         template<typename T>
49         T &value() const
50         {
51                 typedef typename RemoveConst<T>::Type NCT;
52                 Store<NCT> *s=dynamic_cast<Store<NCT> *>(store);
53                 if(!s)
54                         throw InvalidState("Type mismatch");
55                 return s->data;
56         }
57
58         template<typename T>
59         bool check_type() const
60         {
61                 return dynamic_cast<Store<typename RemoveConst<T>::Type> *>(store)!=0;
62         }
63
64         template<typename T>
65         operator T() const
66         { return value<T>(); }
67 };
68
69 } // namespace Msp
70
71 #endif