blob: b9e682ab928b7a7a0b8e9d470e2fae0b986e6528 [file] [log] [blame]
Jim Flynn0dcef532022-06-14 10:58:23 +01001//
2// Copyright (c) MapBox All rights reserved.
3// SPDX-License-Identifier: BSD-3-Clause
4//
5
James Ward22a4e152020-09-25 11:43:21 +01006#ifndef MAPBOX_UTIL_OPTIONAL_HPP
7#define MAPBOX_UTIL_OPTIONAL_HPP
8
9#pragma message("This implementation of optional is deprecated. See https://github.com/mapbox/variant/issues/64.")
10
11#include <type_traits>
12#include <utility>
13
14#include <mapbox/variant.hpp>
15
16namespace mapbox {
17namespace util {
18
19template <typename T>
20class optional
21{
22 static_assert(!std::is_reference<T>::value, "optional doesn't support references");
23
24 struct none_type
25 {
26 };
27
28 variant<none_type, T> variant_;
29
30public:
31 optional() = default;
32
33 optional(optional const& rhs)
34 {
35 if (this != &rhs)
36 { // protect against invalid self-assignment
37 variant_ = rhs.variant_;
38 }
39 }
40
41 optional(T const& v) { variant_ = v; }
42
43 explicit operator bool() const noexcept { return variant_.template is<T>(); }
44
45 T const& get() const { return variant_.template get<T>(); }
46 T& get() { return variant_.template get<T>(); }
47
48 T const& operator*() const { return this->get(); }
49 T operator*() { return this->get(); }
50
51 optional& operator=(T const& v)
52 {
53 variant_ = v;
54 return *this;
55 }
56
57 optional& operator=(optional const& rhs)
58 {
59 if (this != &rhs)
60 {
61 variant_ = rhs.variant_;
62 }
63 return *this;
64 }
65
66 template <typename... Args>
67 void emplace(Args&&... args)
68 {
69 variant_ = T{std::forward<Args>(args)...};
70 }
71
72 void reset() { variant_ = none_type{}; }
73
74}; // class optional
75
76} // namespace util
77} // namespace mapbox
78
79#endif // MAPBOX_UTIL_OPTIONAL_HPP