Treelite
optional.h
Go to the documentation of this file.
1 
8 #ifndef TREELITE_OPTIONAL_H_
9 #define TREELITE_OPTIONAL_H_
10 
11 namespace treelite {
12 
13 template <typename T>
14 class optional { // C++17: Switch to std::optional
15  public:
16  optional() : empty_{}, has_value_{false} {}
17 
18  explicit optional(const T& input_value) : value_{input_value}, has_value_{true} {}
19  optional(optional<T>&& other) : has_value_{other} {
20  if (other) {
21  value_ = *other;
22  }
23  }
24 
25  ~optional() {
26  if (has_value_) {
27  value_.~T();
28  } else {
29  empty_.~empty_byte();
30  }
31  }
32 
33  explicit operator bool() const {
34  return has_value_;
35  }
36  T& operator*() {
37  return value_;
38  }
39  const T& operator*() const {
40  return value_;
41  }
42  T* operator->() {
43  return &value_;
44  }
45  optional& operator=(const T& new_value) {
46  value_ = new_value;
47  has_value_ = true;
48  return *this;
49  }
50 
51  private:
52  struct empty_byte {};
53  union {
54  empty_byte empty_;
55  T value_;
56  };
57  bool has_value_;
58 };
59 
60 } // namespace treelite
61 
62 #endif // TREELITE_OPTIONAL_H_