Global destructor clean-ups and python test fixes
[invirt/third/libt4.git] / maybe.h
1 #ifndef maybe_h
2 #define maybe_h
3
4 #include <cassert>
5
6 template <class T> struct maybe {
7     bool isJust = false;
8     union { T t; };
9     maybe() {}
10     maybe(const maybe & other) {
11         *this = other;
12     }
13     ~maybe() {
14         if (isJust)
15             t.~T();
16     }
17     const maybe & operator =(const maybe & other) {
18         if (isJust) t.~T();
19         isJust = other.isJust;
20         if(isJust) new(&t) T(other.t);
21         return *this;
22     }
23     operator T &() { assert(isJust); return t; }
24     operator bool() { return isJust; }
25 };
26
27 template <class T>
28 static inline maybe<T> nothing() {return maybe<T>();}
29 template <class T>
30 static inline maybe<T> just(const T & t_) { maybe<T> m; m.isJust = true; new(&m.t) T(t_); return m; }
31
32 #endif