Minetest  5.4.0
Optional.h
Go to the documentation of this file.
1 /*
2 Minetest
3 Copyright (C) 2021 rubenwardy
4 
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9 
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
14 
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #pragma once
21 
22 #include "debug.h"
23 
24 struct nullopt_t
25 {
26 };
27 constexpr nullopt_t nullopt{};
28 
37 template <typename T>
38 class Optional
39 {
40  bool m_has_value = false;
42 
43 public:
44  Optional() noexcept {}
45  Optional(nullopt_t) noexcept {}
46  Optional(const T &value) noexcept : m_has_value(true), m_value(value) {}
47  Optional(const Optional<T> &other) noexcept :
48  m_has_value(other.m_has_value), m_value(other.m_value)
49  {
50  }
51 
52  void operator=(nullopt_t) noexcept { m_has_value = false; }
53 
54  void operator=(const Optional<T> &other) noexcept
55  {
56  m_has_value = other.m_has_value;
57  m_value = other.m_value;
58  }
59 
60  T &value()
61  {
62  FATAL_ERROR_IF(!m_has_value, "optional doesn't have value");
63  return m_value;
64  }
65 
66  const T &value() const
67  {
68  FATAL_ERROR_IF(!m_has_value, "optional doesn't have value");
69  return m_value;
70  }
71 
72  const T &value_or(const T &def) const { return m_has_value ? m_value : def; }
73 
74  bool has_value() const noexcept { return m_has_value; }
75 
76  explicit operator bool() const { return m_has_value; }
77 };
constexpr nullopt_t nullopt
Definition: Optional.h:27
An implementation of optional for C++11, which aims to be compatible with a subset of std::optional f...
Definition: Optional.h:39
Optional() noexcept
Definition: Optional.h:44
void operator=(const Optional< T > &other) noexcept
Definition: Optional.h:54
void operator=(nullopt_t) noexcept
Definition: Optional.h:52
Optional(const Optional< T > &other) noexcept
Definition: Optional.h:47
T m_value
Definition: Optional.h:41
Optional(nullopt_t) noexcept
Definition: Optional.h:45
bool has_value() const noexcept
Definition: Optional.h:74
T & value()
Definition: Optional.h:60
bool m_has_value
Definition: Optional.h:40
const T & value() const
Definition: Optional.h:66
const T & value_or(const T &def) const
Definition: Optional.h:72
Optional(const T &value) noexcept
Definition: Optional.h:46
#define FATAL_ERROR_IF(expr, msg)
Definition: debug.h:61
Definition: Optional.h:25