TCPSPSuite
maybe.hpp
1 #ifndef MAYBE_H
2 #define MAYBE_H
3 
4 // TODO c++17 replaces this with std::optional
5 template <class T>
6 class Maybe {
7 public:
8  Maybe(T val_in) : val(val_in), is_valid(true) {}
9 
10  Maybe() : is_valid(false) {}
11 
12  bool
13  valid() const
14  {
15  return this->is_valid;
16  }
17 
18  T &
19  value()
20  {
21  // TODO assertion?
22  return this->val;
23  }
24 
25  const T &
26  value() const
27  {
28  // TODO assertion?
29  return this->val;
30  }
31 
32  operator const T &() const
33  {
34  // TODO assertion?
35  return this->val;
36  }
37 
38  T &
39  value_or_default(T & def)
40  {
41  if (this->is_valid) {
42  return this->val;
43  } else {
44  return def;
45  }
46  }
47 
48  const T &
49  value_or_default(const T & def)
50  {
51  if (this->is_valid) {
52  return this->val;
53  } else {
54  return def;
55  }
56  }
57 
58  const T &
59  value_or_default(const T & def) const
60  {
61  if (this->is_valid) {
62  return this->val;
63  } else {
64  return def;
65  }
66  }
67 
68 private:
69  T val;
70  bool is_valid;
71 };
72 
73 #endif