-
Notifications
You must be signed in to change notification settings - Fork 11
/
variant.h
156 lines (125 loc) · 2.8 KB
/
variant.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#ifndef VARIANT_H
#define VARIANT_H
#include "InkCanvas_global.h"
#ifdef INKCANVAS_QT_VARIANT
#include <QVariant>
INKCANVAS_BEGIN_NAMESPACE
typedef QVariant Variant;
inline bool operator==(Variant const & l, nullptr_t)
{
return l.isNull();
}
inline bool operator!=(Variant const & l, nullptr_t)
{
return !l.isNull();
}
INKCANVAS_END_NAMESPACE
#else
#include <algorithm>
#include <assert.h>
INKCANVAS_BEGIN_NAMESPACE
class Variant
{
public:
template<typename T>
static Variant fromValue(T const & t)
{
return Variant(t);
}
Variant()
{
}
Variant(std::nullptr_t)
{
}
template<typename T>
Variant(T const & t)
{
value_ = new T(t);
copy_ = ©<T>;
equal_ = &equal<T>;
destroy_ = &destroy<T>;
}
template<typename T>
Variant(T const * t)
{
// no need copy & destroy
value_ = t;
copy_ = nullptr;
equal_ = nullptr;
destroy_ = &destroy2<T>;
}
Variant(Variant const & o)
: value_(o.value_)
, copy_(o.copy_)
, equal_(o.equal_)
, destroy_(o.destroy_)
{
if (value_ && copy_)
value_ = copy_(value_);
}
~Variant()
{
if (value_ && destroy_)
destroy_(value_);
value_ = nullptr;
copy_ = nullptr;
destroy_ = nullptr;
}
friend bool operator==(Variant const & l, Variant const & r)
{
return l.destroy_ == r.destroy_
&& (l.equal_ ? l.equal_(l.value_, r.value_) : l.value_ == r.value_);
}
friend bool operator!=(Variant const & l, Variant const & r)
{
return !(l == r);
}
void swap(Variant & o)
{
std::swap(value_, o.value_);
std::swap(copy_, o.copy_);
std::swap(equal_, o.equal_);
std::swap(destroy_, o.destroy_);
}
Variant & operator=(Variant const & o)
{
Variant temp(o);
swap(temp);
return *this;
}
template<typename T>
T & value() const
{
assert(destroy_ == &destroy<T> || destroy_ == &destroy2<T>);
return *reinterpret_cast<T*>(value_);
}
private:
template<typename T>
static void* copy(void * t)
{
return new T(*reinterpret_cast<T*>(t));
}
template<typename T>
static bool equal(void * l, void * r)
{
return *reinterpret_cast<T*>(l) == *reinterpret_cast<T*>(r);
}
template<typename T>
static void destroy(void * t)
{
delete reinterpret_cast<T*>(t);
}
template<typename T>
static void destroy2(void *)
{
}
private:
void * value_ = nullptr;
void* (*copy_)(void*) = nullptr;
bool (*equal_)(void*, void*) = nullptr;
void (*destroy_)(void*) = nullptr;
};
INKCANVAS_END_NAMESPACE
#endif
#endif // VARIANT_H