idol
A C++ Framework for Optimization
Loading...
Searching...
No Matches
Optional.h
1//
2// Created by henri on 01/09/22.
3//
4
5#ifndef OPTIMIZE_OPTIONAL_H
6#define OPTIMIZE_OPTIONAL_H
7
8#include <optional>
9
10namespace idol {
11
12 template<class T>
13 class Optional {
14 T* m_value = nullptr;
15 public:
16 Optional() = default;
17
18 Optional(const Optional<T>& t_optional) : m_value(t_optional.m_value ? new T(*t_optional.m_value) : nullptr) {}
19
20 Optional(Optional<T>&& t_optional) noexcept : m_value(t_optional.m_value) {
21 t_optional.m_value = nullptr;
22 }
23
24 Optional(const T& t_value) : m_value(new T(t_value)) {}
25
26 Optional(T&& t_value) : m_value(new T(std::move(t_value))) {}
27
28 ~Optional() {
29 if (m_value) {
30 delete m_value;
31 }
32 }
33
34 bool has_value() const { return m_value; }
35
36 T& value() {
37 if (!m_value) {
38 throw std::bad_optional_access();
39 }
40 return *m_value;
41 }
42
43 const T& value() const {
44 if (!m_value) {
45 throw std::bad_optional_access();
46 }
47 return *m_value;
48 }
49
50 T& operator*() { return value(); }
51
52 const T& operator*() const { return value(); }
53
54 T* operator->() { return m_value; }
55
56 const T* operator->() const { return m_value; }
57
58 explicit operator bool() const { return m_value; }
59
60 Optional<T>& operator=(T&& t_value) {
61 if (m_value) {
62 delete m_value;
63 }
64 m_value = new T(std::move(t_value));
65 return *this;
66 }
67
68 Optional<T>& operator=(const T& t_value) {
69 if (m_value) {
70 delete m_value;
71 }
72 m_value = new T(t_value);
73 return *this;
74 }
75
76 void reset() {
77 if (m_value) {
78 delete m_value;
79 m_value = nullptr;
80 }
81 }
82
83 template<class ...ArgsT>
84 T& emplace(ArgsT&& ...t_args) {
85 if (m_value) {
86 delete m_value;
87 }
88 m_value = new T(std::forward<ArgsT>(t_args)...);
89 return *m_value;
90 }
91
92 };
93
94 template<class T, class ...ArgsT>
95 Optional<T> make_optional(ArgsT&& ...t_args) {
96 Optional<T> optional;
97 optional.emplace(std::forward<ArgsT>(t_args)...);
98 return optional;
99 }
100}
101
102#endif //OPTIMIZE_OPTIONAL_H