1 // <optional> -*- C++ -*-
3 // Copyright (C) 2013-2020 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file experimental/optional
26 * This is a TS C++ Library header.
30 #ifndef _GLIBCXX_EXPERIMENTAL_OPTIONAL
31 #define _GLIBCXX_EXPERIMENTAL_OPTIONAL 1
33 #if __cplusplus >= 201402L
36 #include <type_traits>
39 #include <initializer_list>
40 #include <bits/functexcept.h>
41 #include <bits/functional_hash.h>
42 #include <bits/enable_special_members.h>
43 #include <experimental/bits/lfts_config.h>
45 namespace std _GLIBCXX_VISIBILITY(default)
47 _GLIBCXX_BEGIN_NAMESPACE_VERSION
49 namespace experimental
51 inline namespace fundamentals_v1
54 * @defgroup optional Optional values
57 * Class template for optional values and surrounding facilities, as
58 * described in n3793 "A proposal to add a utility class to represent
59 * optional objects (Revision 5)".
64 #define __cpp_lib_experimental_optional 201411
66 // All subsequent [X.Y.n] references are against n3793.
69 template<typename _Tp>
73 /// Tag type for in-place construction.
74 struct in_place_t { };
76 /// Tag for in-place construction.
77 constexpr in_place_t in_place { };
80 /// Tag type to disengage optional objects.
83 // Do not user-declare default constructor at all for
84 // optional_value = {} syntax to work.
85 // nullopt_t() = delete;
87 // Used for constructing nullopt.
88 enum class _Construct { _Token };
90 // Must be constexpr for nullopt_t to be literal.
91 explicit constexpr nullopt_t(_Construct) { }
95 /// Tag to disengage optional objects.
96 constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };
100 * @brief Exception class thrown when a disengaged optional object is
102 * @ingroup exceptions
104 class bad_optional_access : public logic_error
107 bad_optional_access() : logic_error("bad optional access") { }
109 // XXX This constructor is non-standard. Should not be inline
110 explicit bad_optional_access(const char* __arg) : logic_error(__arg) { }
112 virtual ~bad_optional_access() noexcept = default;
115 /// @cond undocumented
118 __throw_bad_optional_access(const char*)
119 __attribute__((__noreturn__));
121 // XXX Does not belong here.
123 __throw_bad_optional_access(const char* __s)
124 { _GLIBCXX_THROW_OR_ABORT(bad_optional_access(__s)); }
127 * @brief Class template that holds the necessary state for @ref optional
128 * and that has the responsibility for construction and the special members.
130 * Such a separate base class template is necessary in order to
131 * conditionally enable the special members (e.g. copy/move constructors).
132 * Note that this means that @ref _Optional_base implements the
133 * functionality for copy and move assignment, but not for converting
136 * @see optional, _Enable_special_members
138 template<typename _Tp, bool _ShouldProvideDestructor =
139 !is_trivially_destructible<_Tp>::value>
143 // Remove const to avoid prohibition of reusing object storage for
144 // const-qualified types in [3.8/9]. This is strictly internal
145 // and even optional itself is oblivious to it.
146 using _Stored_type = remove_const_t<_Tp>;
149 // [X.Y.4.1] Constructors.
151 // Constructors for disengaged optionals.
152 constexpr _Optional_base() noexcept
155 constexpr _Optional_base(nullopt_t) noexcept
156 : _Optional_base{} { }
158 // Constructors for engaged optionals.
159 template<typename... _Args>
160 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
161 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
163 template<typename _Up, typename... _Args,
164 enable_if_t<is_constructible<_Tp,
165 initializer_list<_Up>&,
168 constexpr explicit _Optional_base(in_place_t,
169 initializer_list<_Up> __il,
171 : _M_payload(__il, std::forward<_Args>(__args)...),
174 // Copy and move constructors.
175 _Optional_base(const _Optional_base& __other)
177 if (__other._M_engaged)
178 this->_M_construct(__other._M_get());
181 _Optional_base(_Optional_base&& __other)
182 noexcept(is_nothrow_move_constructible<_Tp>())
184 if (__other._M_engaged)
185 this->_M_construct(std::move(__other._M_get()));
188 // [X.Y.4.3] (partly) Assignment.
190 operator=(const _Optional_base& __other)
192 if (this->_M_engaged && __other._M_engaged)
193 this->_M_get() = __other._M_get();
196 if (__other._M_engaged)
197 this->_M_construct(__other._M_get());
206 operator=(_Optional_base&& __other)
207 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
208 is_nothrow_move_assignable<_Tp>>())
210 if (this->_M_engaged && __other._M_engaged)
211 this->_M_get() = std::move(__other._M_get());
214 if (__other._M_engaged)
215 this->_M_construct(std::move(__other._M_get()));
222 // [X.Y.4.2] Destructor.
225 if (this->_M_engaged)
226 this->_M_payload.~_Stored_type();
229 // The following functionality is also needed by optional, hence the
230 // protected accessibility.
232 constexpr bool _M_is_engaged() const noexcept
233 { return this->_M_engaged; }
235 // The _M_get operations have _M_engaged as a precondition.
238 { return _M_payload; }
241 _M_get() const noexcept
242 { return _M_payload; }
244 // The _M_construct operation has !_M_engaged as a precondition
245 // while _M_destruct has _M_engaged as a precondition.
246 template<typename... _Args>
248 _M_construct(_Args&&... __args)
249 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
251 ::new (std::__addressof(this->_M_payload))
252 _Stored_type(std::forward<_Args>(__args)...);
253 this->_M_engaged = true;
259 this->_M_engaged = false;
260 this->_M_payload.~_Stored_type();
263 // _M_reset is a 'safe' operation with no precondition.
267 if (this->_M_engaged)
272 struct _Empty_byte { };
274 _Empty_byte _M_empty;
275 _Stored_type _M_payload;
277 bool _M_engaged = false;
280 /// Partial specialization that is exactly identical to the primary template
281 /// save for not providing a destructor, to fulfill triviality requirements.
282 template<typename _Tp>
283 class _Optional_base<_Tp, false>
286 using _Stored_type = remove_const_t<_Tp>;
289 constexpr _Optional_base() noexcept
292 constexpr _Optional_base(nullopt_t) noexcept
293 : _Optional_base{} { }
295 template<typename... _Args>
296 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
297 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
299 template<typename _Up, typename... _Args,
300 enable_if_t<is_constructible<_Tp,
301 initializer_list<_Up>&,
304 constexpr explicit _Optional_base(in_place_t,
305 initializer_list<_Up> __il,
307 : _M_payload(__il, std::forward<_Args>(__args)...),
310 _Optional_base(const _Optional_base& __other)
312 if (__other._M_engaged)
313 this->_M_construct(__other._M_get());
316 _Optional_base(_Optional_base&& __other)
317 noexcept(is_nothrow_move_constructible<_Tp>())
319 if (__other._M_engaged)
320 this->_M_construct(std::move(__other._M_get()));
324 operator=(const _Optional_base& __other)
326 if (this->_M_engaged && __other._M_engaged)
327 this->_M_get() = __other._M_get();
330 if (__other._M_engaged)
331 this->_M_construct(__other._M_get());
339 operator=(_Optional_base&& __other)
340 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
341 is_nothrow_move_assignable<_Tp>>())
343 if (this->_M_engaged && __other._M_engaged)
344 this->_M_get() = std::move(__other._M_get());
347 if (__other._M_engaged)
348 this->_M_construct(std::move(__other._M_get()));
356 // ~_Optional_base() noexcept = default;
359 constexpr bool _M_is_engaged() const noexcept
360 { return this->_M_engaged; }
364 { return _M_payload; }
367 _M_get() const noexcept
368 { return _M_payload; }
370 template<typename... _Args>
372 _M_construct(_Args&&... __args)
373 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
375 ::new (std::__addressof(this->_M_payload))
376 _Stored_type(std::forward<_Args>(__args)...);
377 this->_M_engaged = true;
383 this->_M_engaged = false;
384 this->_M_payload.~_Stored_type();
390 if (this->_M_engaged)
395 struct _Empty_byte { };
398 _Empty_byte _M_empty;
399 _Stored_type _M_payload;
401 bool _M_engaged = false;
404 template<typename _Tp, typename _Up>
405 using __converts_from_optional =
406 __or_<is_constructible<_Tp, const optional<_Up>&>,
407 is_constructible<_Tp, optional<_Up>&>,
408 is_constructible<_Tp, const optional<_Up>&&>,
409 is_constructible<_Tp, optional<_Up>&&>,
410 is_convertible<const optional<_Up>&, _Tp>,
411 is_convertible<optional<_Up>&, _Tp>,
412 is_convertible<const optional<_Up>&&, _Tp>,
413 is_convertible<optional<_Up>&&, _Tp>>;
415 template<typename _Tp, typename _Up>
416 using __assigns_from_optional =
417 __or_<is_assignable<_Tp&, const optional<_Up>&>,
418 is_assignable<_Tp&, optional<_Up>&>,
419 is_assignable<_Tp&, const optional<_Up>&&>,
420 is_assignable<_Tp&, optional<_Up>&&>>;
425 * @brief Class template for optional values.
427 template<typename _Tp>
429 : private _Optional_base<_Tp>,
430 private _Enable_copy_move<
432 is_copy_constructible<_Tp>::value,
434 __and_<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>::value,
436 is_move_constructible<_Tp>::value,
438 __and_<is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value,
442 static_assert(__and_<__not_<is_same<remove_cv_t<_Tp>, nullopt_t>>,
443 __not_<is_same<remove_cv_t<_Tp>, in_place_t>>,
444 __not_<is_reference<_Tp>>>(),
445 "Invalid instantiation of optional<T>");
448 using _Base = _Optional_base<_Tp>;
451 using value_type = _Tp;
453 // _Optional_base has the responsibility for construction.
456 constexpr optional() = default;
457 // Converting constructors for engaged optionals.
458 template <typename _Up = _Tp,
460 __not_<is_same<optional<_Tp>, decay_t<_Up>>>,
461 is_constructible<_Tp, _Up&&>,
462 is_convertible<_Up&&, _Tp>
463 >::value, bool> = true>
464 constexpr optional(_Up&& __t)
465 : _Base(in_place, std::forward<_Up>(__t)) { }
467 template <typename _Up = _Tp,
469 __not_<is_same<optional<_Tp>, decay_t<_Up>>>,
470 is_constructible<_Tp, _Up&&>,
471 __not_<is_convertible<_Up&&, _Tp>>
472 >::value, bool> = false>
473 explicit constexpr optional(_Up&& __t)
474 : _Base(in_place, std::forward<_Up>(__t)) { }
476 template <typename _Up,
478 __not_<is_same<_Tp, _Up>>,
479 is_constructible<_Tp, const _Up&>,
480 is_convertible<const _Up&, _Tp>,
481 __not_<__converts_from_optional<_Tp, _Up>>
482 >::value, bool> = true>
483 constexpr optional(const optional<_Up>& __t)
489 template <typename _Up,
491 __not_<is_same<_Tp, _Up>>,
492 is_constructible<_Tp, const _Up&>,
493 __not_<is_convertible<const _Up&, _Tp>>,
494 __not_<__converts_from_optional<_Tp, _Up>>
495 >::value, bool> = false>
496 explicit constexpr optional(const optional<_Up>& __t)
502 template <typename _Up,
504 __not_<is_same<_Tp, _Up>>,
505 is_constructible<_Tp, _Up&&>,
506 is_convertible<_Up&&, _Tp>,
507 __not_<__converts_from_optional<_Tp, _Up>>
508 >::value, bool> = true>
509 constexpr optional(optional<_Up>&& __t)
512 emplace(std::move(*__t));
515 template <typename _Up,
517 __not_<is_same<_Tp, _Up>>,
518 is_constructible<_Tp, _Up&&>,
519 __not_<is_convertible<_Up&&, _Tp>>,
520 __not_<__converts_from_optional<_Tp, _Up>>
521 >::value, bool> = false>
522 explicit constexpr optional(optional<_Up>&& __t)
525 emplace(std::move(*__t));
528 // [X.Y.4.3] (partly) Assignment.
530 operator=(nullopt_t) noexcept
536 template<typename _Up = _Tp>
538 __not_<is_same<optional<_Tp>, decay_t<_Up>>>,
539 is_constructible<_Tp, _Up>,
540 __not_<__and_<is_scalar<_Tp>,
541 is_same<_Tp, decay_t<_Up>>>>,
542 is_assignable<_Tp&, _Up>>::value,
546 if (this->_M_is_engaged())
547 this->_M_get() = std::forward<_Up>(__u);
549 this->_M_construct(std::forward<_Up>(__u));
554 template<typename _Up>
556 __not_<is_same<_Tp, _Up>>,
557 is_constructible<_Tp, const _Up&>,
558 is_assignable<_Tp&, _Up>,
559 __not_<__converts_from_optional<_Tp, _Up>>,
560 __not_<__assigns_from_optional<_Tp, _Up>>
563 operator=(const optional<_Up>& __u)
567 if (this->_M_is_engaged())
568 this->_M_get() = *__u;
570 this->_M_construct(*__u);
579 template<typename _Up>
581 __not_<is_same<_Tp, _Up>>,
582 is_constructible<_Tp, _Up>,
583 is_assignable<_Tp&, _Up>,
584 __not_<__converts_from_optional<_Tp, _Up>>,
585 __not_<__assigns_from_optional<_Tp, _Up>>
588 operator=(optional<_Up>&& __u)
592 if (this->_M_is_engaged())
593 this->_M_get() = std::move(*__u);
595 this->_M_construct(std::move(*__u));
605 template<typename... _Args>
606 enable_if_t<is_constructible<_Tp, _Args&&...>::value>
607 emplace(_Args&&... __args)
610 this->_M_construct(std::forward<_Args>(__args)...);
613 template<typename _Up, typename... _Args>
614 enable_if_t<is_constructible<_Tp, initializer_list<_Up>&,
616 emplace(initializer_list<_Up> __il, _Args&&... __args)
619 this->_M_construct(__il, std::forward<_Args>(__args)...);
622 // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base.
626 swap(optional& __other)
627 noexcept(is_nothrow_move_constructible<_Tp>()
628 && __is_nothrow_swappable<_Tp>::value)
632 if (this->_M_is_engaged() && __other._M_is_engaged())
633 swap(this->_M_get(), __other._M_get());
634 else if (this->_M_is_engaged())
636 __other._M_construct(std::move(this->_M_get()));
639 else if (__other._M_is_engaged())
641 this->_M_construct(std::move(__other._M_get()));
642 __other._M_destruct();
646 // [X.Y.4.5] Observers.
649 { return std::__addressof(this->_M_get()); }
653 { return std::__addressof(this->_M_get()); }
657 { return this->_M_get(); }
661 { return this->_M_get(); }
665 { return std::move(this->_M_get()); }
667 constexpr const _Tp&&
669 { return std::move(this->_M_get()); }
671 constexpr explicit operator bool() const noexcept
672 { return this->_M_is_engaged(); }
677 return this->_M_is_engaged()
679 : (__throw_bad_optional_access("Attempt to access value of a "
680 "disengaged optional object"),
687 return this->_M_is_engaged()
689 : (__throw_bad_optional_access("Attempt to access value of a "
690 "disengaged optional object"),
697 return this->_M_is_engaged()
698 ? std::move(this->_M_get())
699 : (__throw_bad_optional_access("Attempt to access value of a "
700 "disengaged optional object"),
701 std::move(this->_M_get()));
704 constexpr const _Tp&&
707 return this->_M_is_engaged()
708 ? std::move(this->_M_get())
709 : (__throw_bad_optional_access("Attempt to access value of a "
710 "disengaged optional object"),
711 std::move(this->_M_get()));
714 template<typename _Up>
716 value_or(_Up&& __u) const&
718 static_assert(__and_<is_copy_constructible<_Tp>,
719 is_convertible<_Up&&, _Tp>>(),
720 "Cannot return value");
722 return this->_M_is_engaged()
724 : static_cast<_Tp>(std::forward<_Up>(__u));
727 template<typename _Up>
729 value_or(_Up&& __u) &&
731 static_assert(__and_<is_move_constructible<_Tp>,
732 is_convertible<_Up&&, _Tp>>(),
733 "Cannot return value" );
735 return this->_M_is_engaged()
736 ? std::move(this->_M_get())
737 : static_cast<_Tp>(std::forward<_Up>(__u));
741 /// @relates experimental::optional @{
743 // [X.Y.8] Comparisons between optional values.
744 template<typename _Tp>
746 operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
748 return static_cast<bool>(__lhs) == static_cast<bool>(__rhs)
749 && (!__lhs || *__lhs == *__rhs);
752 template<typename _Tp>
754 operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
755 { return !(__lhs == __rhs); }
757 template<typename _Tp>
759 operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
761 return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs);
764 template<typename _Tp>
766 operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
767 { return __rhs < __lhs; }
769 template<typename _Tp>
771 operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
772 { return !(__rhs < __lhs); }
774 template<typename _Tp>
776 operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
777 { return !(__lhs < __rhs); }
779 // [X.Y.9] Comparisons with nullopt.
780 template<typename _Tp>
782 operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept
785 template<typename _Tp>
787 operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept
790 template<typename _Tp>
792 operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept
793 { return static_cast<bool>(__lhs); }
795 template<typename _Tp>
797 operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept
798 { return static_cast<bool>(__rhs); }
800 template<typename _Tp>
802 operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
805 template<typename _Tp>
807 operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept
808 { return static_cast<bool>(__rhs); }
810 template<typename _Tp>
812 operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept
813 { return static_cast<bool>(__lhs); }
815 template<typename _Tp>
817 operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
820 template<typename _Tp>
822 operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept
825 template<typename _Tp>
827 operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
830 template<typename _Tp>
832 operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
835 template<typename _Tp>
837 operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept
840 // [X.Y.10] Comparisons with value type.
841 template<typename _Tp>
843 operator==(const optional<_Tp>& __lhs, const _Tp& __rhs)
844 { return __lhs && *__lhs == __rhs; }
846 template<typename _Tp>
848 operator==(const _Tp& __lhs, const optional<_Tp>& __rhs)
849 { return __rhs && __lhs == *__rhs; }
851 template<typename _Tp>
853 operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs)
854 { return !__lhs || !(*__lhs == __rhs); }
856 template<typename _Tp>
858 operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs)
859 { return !__rhs || !(__lhs == *__rhs); }
861 template<typename _Tp>
863 operator<(const optional<_Tp>& __lhs, const _Tp& __rhs)
864 { return !__lhs || *__lhs < __rhs; }
866 template<typename _Tp>
868 operator<(const _Tp& __lhs, const optional<_Tp>& __rhs)
869 { return __rhs && __lhs < *__rhs; }
871 template<typename _Tp>
873 operator>(const optional<_Tp>& __lhs, const _Tp& __rhs)
874 { return __lhs && __rhs < *__lhs; }
876 template<typename _Tp>
878 operator>(const _Tp& __lhs, const optional<_Tp>& __rhs)
879 { return !__rhs || *__rhs < __lhs; }
881 template<typename _Tp>
883 operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs)
884 { return !__lhs || !(__rhs < *__lhs); }
886 template<typename _Tp>
888 operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs)
889 { return __rhs && !(*__rhs < __lhs); }
891 template<typename _Tp>
893 operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs)
894 { return __lhs && !(*__lhs < __rhs); }
896 template<typename _Tp>
898 operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs)
899 { return !__rhs || !(__lhs < *__rhs); }
902 template<typename _Tp>
904 swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs)
905 noexcept(noexcept(__lhs.swap(__rhs)))
906 { __lhs.swap(__rhs); }
908 template<typename _Tp>
909 constexpr optional<decay_t<_Tp>>
910 make_optional(_Tp&& __t)
911 { return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; }
913 /// @} relates experimental::optional
914 /// @} group optional
915 } // namespace fundamentals_v1
916 } // namespace experimental
919 /// std::hash partial specialization for experimental::optional
920 /// @relates experimental::optional
921 template<typename _Tp>
922 struct hash<experimental::optional<_Tp>>
924 using result_type = size_t;
925 using argument_type = experimental::optional<_Tp>;
928 operator()(const experimental::optional<_Tp>& __t) const
929 noexcept(noexcept(hash<_Tp> {}(*__t)))
931 // We pick an arbitrary hash for disengaged optionals which hopefully
932 // usual values of _Tp won't typically hash to.
933 constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333);
934 return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash;
938 _GLIBCXX_END_NAMESPACE_VERSION
943 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL