Xmipp  v3.23.11-Nereus
optional.h
Go to the documentation of this file.
1 /*
2  * optional.h
3  *
4  * Created on: Dec 12, 2018
5  * Author: david
6  */
7 
8 #ifndef CORE_OPTIONAL_H_
9 #define CORE_OPTIONAL_H_
10 
11 #if __cplusplus >= 201703L
12 #include <optional>
13 namespace core{
14 using std::optional;
15 }
16 #else
17 
18 #include <utility>
19 #include <assert.h>
20 
21 namespace core {
22 
23 template<typename T>
24 class optional {
25 public:
27  p(new payload()) {
28  }
29  ;
30  optional(const T &&t) :
31  p(new payload_full(t)) {
32  }
33  ;
34 
35  optional(const T &t) :
36  p(new payload_full(t)) {
37  }
38  ;
39 
40  optional(const optional &&o) {
41  delete p;
42  this->p = o.p;
43  }
44 
46  if (this != &o) {
47  delete p;
48  this->p = o.p;
49  o.p = nullptr;
50  }
51  return *this;
52  }
53 
55  delete p;
56  p = nullptr;
57  }
58 
59  constexpr explicit operator bool() const {
60  return p->has_value;
61  }
62 
63  constexpr bool has_value() const {
64  return p->has_value;
65  }
66 
67  inline T& value() const {
68  assert(p->has_value);
69  return static_cast<payload_full*>(p)->t;
70  }
71 
72 private:
73 
74  struct payload {
75  explicit payload(bool has_value = false) :
77  }
78  ;
79  const bool has_value;
80  };
81 
82  struct payload_full: public payload {
83  explicit payload_full(const T &t) :
84  payload(true), t(std::move(t)) {
85  }
86  ;
87 
88  T t;
89  };
90 
91  payload *p;
92 
93 };
94 // optional
95 
96 }// namespace
97 
98 #endif
99 #endif /* CORE_OPTIONAL_H_ */
T & value() const
Definition: optional.h:67
Definition: optional.h:21
optional(const optional &&o)
Definition: optional.h:40
optional(const T &&t)
Definition: optional.h:30
optional(const T &t)
Definition: optional.h:35
constexpr bool has_value() const
Definition: optional.h:63
optional & operator=(optional &&o)
Definition: optional.h:45