-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsum.h
118 lines (105 loc) · 2.5 KB
/
sum.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
#ifndef SFL_SUM_H
#define SFL_SUM_H
#include <cassert>
#include <cstdint>
namespace sfl
{
/**
* Algebraic data type, a.k.a. typesafe union. Now it can only have two members but it would be nice
* if we would generalize this to more variables, while retaining vs2013 compatibility in the future. Use the match()
* function to get variable, this can be thought of a pseudo-guard. match() needs a template parameter which is the
* return value.
*
* usage example:
* sum<int, std::string> value = "this is a string"
*
* auto meaning = match<size_t>(value, [](int a){return 42 + al},
* [](const std::string &a){return a.length();});
*/
template<typename T0, typename T1>
class sum final {
public:
sum(const T0 &value) :
_currentType(0)
{
new (_storage) T0(value);
}
sum(const T1 &value) :
_currentType(1)
{
new (_storage) T1(value);
}
public:
sum(const sum<T0,T1> &rhs)
{
assign(rhs);
}
sum<T0,T1> &operator=(const sum<T0,T1> &rhs)
{
if (_currentType == rhs._currentType) {
switch(_currentType) {
case 0:
*reinterpret_cast<T0 *>(&_storage) = *reinterpret_cast<const T0 *>(&rhs._storage);
break;
case 1:
*reinterpret_cast<T1 *>(&_storage) = *reinterpret_cast<const T1 *>(&rhs._storage);
break;
}
} else {
resign();
assign(rhs);
}
return *this;
}
~sum()
{
resign();
}
typedef T0 type0;
typedef T1 type1;
template<typename R, typename F0, typename F1>
R match(F0 &&f0, F1 &&f1) const
{
switch (_currentType) {
case 0:
return f0(*reinterpret_cast<const T0 *>(&_storage));
case 1:
return f1(*reinterpret_cast<const T1 *>(&_storage));
}
assert(false);
}
private:
void assign(const sum<T0,T1> &rhs)
{
_currentType = rhs._currentType;
switch(_currentType) {
case 0:
new (_storage) T0(*reinterpret_cast<const T0 *>(&rhs._storage));
break;
case 1:
new (_storage) T1(*reinterpret_cast<const T1 *>(&rhs._storage));
break;
}
}
void resign()
{
switch (_currentType) {
case 0:
(*reinterpret_cast<T0 *>(&_storage)).~T0();
break;
case 1:
(*reinterpret_cast<T1 *>(&_storage)).~T1();
break;
}
}
// storage comes first for proper alignment
uint8_t _storage[(sizeof(T0) > sizeof(T1)) ? sizeof(T0) : sizeof(T1)];
uint8_t _currentType;
};
template<typename R, typename V, typename F0, typename F1>
R match(const V &v, F0 &&f0, F1 &&f1)
{
return v.template match<R>(f0, f1);
}
}
#endif