TouchCPLib  1.0.0
A touch-enabled GUI interface based on SDL and libTS. It provides a simple desktop-free UI for your embedded Raspberry projects.
Optional.h
Go to the documentation of this file.
1 #pragma once
2 
13 #include <memory>
14 
20 template <typename T>
21 class Optional
22 {
23 public:
27  Optional() {}
33  Optional(const T &value) { innerValue = std::unique_ptr<T>(new T(value)); } // copy
39  Optional(T &&value) { innerValue = std::unique_ptr<T>(new T(std::move(value))); } // move
45  bool hasValue() const { return innerValue != nullptr; }
52  T &get()
53  {
54  T *innerPtr = innerValue.get();
55  if (innerPtr != nullptr)
56  return *innerPtr;
57  else
58  throw std::runtime_error("Can't extract a reference from a null pointer");
59  }
66  const T &get() const
67  {
68  T *innerPtr = innerValue.get();
69  if (innerPtr != nullptr)
70  return *innerPtr;
71  else
72  throw std::runtime_error("Can't extract a reference from a null pointer");
73  }
79  void set(const T &value) { innerValue.reset(new T(value)); }
85  void set(T &&value) { innerValue.reset(new T(value)); }
93  {
94  if (!value.hasValue())
95  innerValue.reset();
96  else
97  innerValue.reset(new T(value.get())); // copy
98  return *this;
99  }
104  void clear() { innerValue.reset(); }
105 
106 private:
107  std::unique_ptr<T> innerValue = nullptr;
108 };
bool hasValue() const
Returns true if the optional object has a value.
Definition: Optional.h:45
T & get()
Gets the inner object.
Definition: Optional.h:52
Optional(T &&value)
Construct an Optional object initialized with the given value.
Definition: Optional.h:39
Optional(const T &value)
Construct an Optional object initialized with the given value.
Definition: Optional.h:33
A class that wraps a value that can be null.
Definition: Optional.h:21
Optional()
Construct an empty Optional object.
Definition: Optional.h:27
Optional< T > & operator=(const Optional< T > &value)
Assignment operator with copy semantics.
Definition: Optional.h:92
void clear()
Removes the inner object, making the optional void.
Definition: Optional.h:104