]> git.tdb.fi Git - libs/core.git/blob - source/core/variant.h
b81bb506f300f8df2f215a63a427a7df38af7f7e
[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
13 namespace Msp {
14
15 class Variant
16 {
17 private:
18         struct StoreBase
19         {
20                 virtual ~StoreBase() { }
21         };
22
23         template<typename T>
24         struct Store: public StoreBase
25         {
26                 T data;
27
28                 Store(T d): data(d) { }
29         };
30
31         StoreBase *store;
32
33 public:
34         Variant(): store(0) { }
35         template<typename T>
36         Variant(T v): store(new Store<T>(v)) { }
37         ~Variant() { delete store; }
38
39         template<typename T>
40         Variant &operator=(T v)
41         {
42                 delete store;
43                 store=new Store<T>(v);
44                 return *this;
45         }
46
47         template<typename T>
48         T value() const
49         {
50                 Store<T> *s=dynamic_cast<Store<T> *>(store);
51                 if(!s)
52                         throw InvalidState("Type mismatch");
53                 return s->data;
54         }
55
56         template<typename T>
57         bool check_type() const
58         {
59                 return dynamic_cast<Store<T> *>(store)!=0;
60         }
61
62         template<typename T>
63         operator T() const
64         { return value<T>(); }
65 };
66
67 } // namespace Msp
68
69 #endif