1 // 2 // Copyright (c) MapBox All rights reserved. 3 // SPDX-License-Identifier: BSD-3-Clause 4 // 5 6 #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 16 namespace mapbox { 17 namespace util { 18 19 template <typename T> 20 class 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 30 public: 31 optional() = default; 32 optional(optional const & rhs)33 optional(optional const& rhs) 34 { 35 if (this != &rhs) 36 { // protect against invalid self-assignment 37 variant_ = rhs.variant_; 38 } 39 } 40 optional(T const & v)41 optional(T const& v) { variant_ = v; } 42 operator bool() const43 explicit operator bool() const noexcept { return variant_.template is<T>(); } 44 get() const45 T const& get() const { return variant_.template get<T>(); } get()46 T& get() { return variant_.template get<T>(); } 47 operator *() const48 T const& operator*() const { return this->get(); } operator *()49 T operator*() { return this->get(); } 50 operator =(T const & v)51 optional& operator=(T const& v) 52 { 53 variant_ = v; 54 return *this; 55 } 56 operator =(optional const & rhs)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> emplace(Args &&...args)67 void emplace(Args&&... args) 68 { 69 variant_ = T{std::forward<Args>(args)...}; 70 } 71 reset()72 void reset() { variant_ = none_type{}; } 73 74 }; // class optional 75 76 } // namespace util 77 } // namespace mapbox 78 79 #endif // MAPBOX_UTIL_OPTIONAL_HPP 80