tenno 0.1.0
Loading...
Searching...
No Matches
optional.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Author: Giovanni Santini
3// Mail: giovanni.santini@proton.me
4// Github: @San7o
5
6#pragma once
7
8#include <tenno/algorithm.hpp>
9#include <type_traits> // std::is_constant_evaluated
10
11namespace tenno
12{
13
23template <typename T> class optional
24{
25public:
29 using value_type = T;
30
34 constexpr optional() noexcept : _has_value(false)
35 {
36#if __cplusplus >= 202002L // C++20
37 if (std::is_constant_evaluated())
38 {
39#endif
40 _value = T();
41#if __cplusplus >= 202002L // C++20
42 }
43#endif
44 }
45
46 constexpr optional(T value) noexcept : _has_value(true), _value(value)
47 {
48 }
49
51 {
52 this = optional(value);
53 }
54
55 constexpr T operator->() const noexcept
56 {
57 return this->_value;
58 }
59
60 constexpr T operator*() const noexcept
61 {
62 return this->_value;
63 }
64
65 constexpr bool has_value() const noexcept
66 {
67 return this->_has_value;
68 }
69
70 constexpr T value() const noexcept
71 {
72 return this->_value;
73 }
74
82 constexpr T value_or(const T &other) const noexcept
83 {
84 if (this->_has_value)
85 return this->_value;
86 return other;
87 }
88
94 void swap(optional &other) noexcept
95 {
96 if (this->_has_value && other.has_value())
97 tenno::swap(*this, other);
98 }
99
100 void reset() noexcept
101 {
102 if (this->_has_value)
103 this->_value.~T();
104 *this = optional();
105 }
106
114 template <class... Args> T &emplace(Args &&...args)
115 {
116 *this = optional(T(args...));
117 return this->_value;
118 }
119
120private:
121 bool _has_value;
122 union
123 {
125 };
126};
127
128} // namespace tenno
An optional value.
Definition optional.hpp:24
constexpr T value() const noexcept
Definition optional.hpp:70
constexpr optional() noexcept
Constructs an optional that does not contain a value.
Definition optional.hpp:34
T value_type
The type of the optional value.
Definition optional.hpp:29
constexpr T operator->() const noexcept
Definition optional.hpp:55
constexpr T operator*() const noexcept
Definition optional.hpp:60
constexpr optional(T value) noexcept
Definition optional.hpp:46
void swap(optional &other) noexcept
Swaps the optional with another optional.
Definition optional.hpp:94
constexpr T value_or(const T &other) const noexcept
Returns the value of the optional or a default value.
Definition optional.hpp:82
optional operator=(T &value) noexcept
Definition optional.hpp:50
T & emplace(Args &&...args)
Constructs the value in place.
Definition optional.hpp:114
void reset() noexcept
Definition optional.hpp:100
constexpr bool has_value() const noexcept
Definition optional.hpp:65
void swap(T &a, T &b) noexcept
Exchanges the values of a and b.
Definition algorithm.hpp:99