1 // <optional> -*- C++ -*-
3 // Copyright (C) 2013-2014 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.
29 #ifndef _GLIBCXX_EXPERIMENTAL_OPTIONAL
30 #define _GLIBCXX_EXPERIMENTAL_OPTIONAL 1
33 * @defgroup experimental Experimental
35 * Components specified by various Technical Specifications.
38 #if __cplusplus <= 201103L
39 # include <bits/c++14_warning.h>
43 #include <type_traits>
46 #include <initializer_list>
47 #include <bits/functexcept.h>
48 #include <bits/functional_hash.h>
49 #include <bits/enable_special_members.h>
51 namespace std _GLIBCXX_VISIBILITY(default)
53 namespace experimental
55 _GLIBCXX_BEGIN_NAMESPACE_VERSION
58 * @defgroup optional Optional values
59 * @ingroup experimental
61 * Class template for optional values and surrounding facilities, as
62 * described in n3793 "A proposal to add a utility class to represent
63 * optional objects (Revision 5)".
68 // All subsequent [X.Y.n] references are against n3793.
71 template<typename _Tp>
75 /// Tag type for in-place construction.
76 struct in_place_t { };
78 /// Tag for in-place construction.
79 constexpr in_place_t in_place { };
82 /// Tag type to disengage optional objects.
85 // Do not user-declare default constructor at all for
86 // optional_value = {} syntax to work.
87 // nullopt_t() = delete;
89 // Used for constructing nullopt.
90 enum class _Construct { _Token };
92 // Must be constexpr for nullopt_t to be literal.
93 explicit constexpr nullopt_t(_Construct) { }
97 /// Tag to disengage optional objects.
98 constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };
102 * @brief Exception class thrown when a disengaged optional object is
104 * @ingroup exceptions
106 class bad_optional_access : public logic_error
109 bad_optional_access() : logic_error("bad optional access") { }
111 // XXX This constructor is non-standard. Should not be inline
112 explicit bad_optional_access(const char* __arg) : logic_error(__arg) { }
114 virtual ~bad_optional_access() noexcept = default;
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)); }
126 template<typename _Tp, typename _Sfinae = void>
127 struct _Has_addressof_impl : std::false_type { };
129 template<typename _Tp>
130 struct _Has_addressof_impl<_Tp,
131 decltype( std::declval<const _Tp&>().operator&(), void() )>
132 : std::true_type { };
135 * @brief Trait that detects the presence of an overloaded unary operator&.
137 * Practically speaking this detects the presence of such an operator when
138 * called on a const-qualified lvalue (i.e.
139 * declval<_Tp * const&>().operator&()).
141 template<typename _Tp>
142 struct _Has_addressof : _Has_addressof_impl<_Tp>::type { };
145 * @brief An overload that attempts to take the address of an lvalue as a
146 * constant expression. Falls back to __addressof in the presence of an
147 * overloaded addressof operator (unary operator&), in which case the call
148 * will not be a constant expression.
150 template<typename _Tp, typename enable_if<!_Has_addressof<_Tp>::value,
152 constexpr _Tp* __constexpr_addressof(_Tp& __t)
156 * @brief Fallback overload that defers to __addressof.
158 template<typename _Tp, typename enable_if<_Has_addressof<_Tp>::value,
160 inline _Tp* __constexpr_addressof(_Tp& __t)
161 { return std::__addressof(__t); }
164 * @brief Class template that holds the necessary state for @ref optional
165 * and that has the responsibility for construction and the special members.
167 * Such a separate base class template is necessary in order to
168 * conditionally enable the special members (e.g. copy/move constructors).
169 * Note that this means that @ref _Optional_base implements the
170 * functionality for copy and move assignment, but not for converting
173 * @see optional, _Enable_special_members
175 template<typename _Tp, bool _ShouldProvideDestructor =
176 !is_trivially_destructible<_Tp>::value>
180 // Remove const to avoid prohibition of reusing object storage for
181 // const-qualified types in [3.8/9]. This is strictly internal
182 // and even optional itself is oblivious to it.
183 using _Stored_type = typename remove_const<_Tp>::type;
186 // [X.Y.4.1] Constructors.
188 // Constructors for disengaged optionals.
189 constexpr _Optional_base() noexcept
192 constexpr _Optional_base(nullopt_t) noexcept
193 : _Optional_base{} { }
195 // Constructors for engaged optionals.
196 constexpr _Optional_base(const _Tp& __t)
197 : _M_payload(__t), _M_engaged(true) { }
199 constexpr _Optional_base(_Tp&& __t)
200 : _M_payload(std::move(__t)), _M_engaged(true) { }
202 template<typename... _Args>
203 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
204 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
206 template<typename _Up, typename... _Args,
207 typename enable_if<is_constructible<_Tp,
208 initializer_list<_Up>&,
211 constexpr explicit _Optional_base(in_place_t,
212 initializer_list<_Up> __il,
214 : _M_payload(__il, std::forward<_Args>(__args)...),
217 // Copy and move constructors.
218 _Optional_base(const _Optional_base& __other)
220 if (__other._M_engaged)
221 this->_M_construct(__other._M_get());
224 _Optional_base(_Optional_base&& __other)
225 noexcept(is_nothrow_move_constructible<_Tp>())
227 if (__other._M_engaged)
228 this->_M_construct(std::move(__other._M_get()));
231 // [X.Y.4.3] (partly) Assignment.
233 operator=(const _Optional_base& __other)
235 if (this->_M_engaged && __other._M_engaged)
236 this->_M_get() = __other._M_get();
239 if (__other._M_engaged)
240 this->_M_construct(__other._M_get());
249 operator=(_Optional_base&& __other)
250 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
251 is_nothrow_move_assignable<_Tp>>())
253 if (this->_M_engaged && __other._M_engaged)
254 this->_M_get() = std::move(__other._M_get());
257 if (__other._M_engaged)
258 this->_M_construct(std::move(__other._M_get()));
265 // [X.Y.4.2] Destructor.
268 if (this->_M_engaged)
269 this->_M_payload.~_Stored_type();
272 // The following functionality is also needed by optional, hence the
273 // protected accessibility.
275 constexpr bool _M_is_engaged() const noexcept
276 { return this->_M_engaged; }
278 // The _M_get operations have _M_engaged as a precondition.
281 { return _M_payload; }
284 _M_get() const noexcept
285 { return _M_payload; }
287 // The _M_construct operation has !_M_engaged as a precondition
288 // while _M_destruct has _M_engaged as a precondition.
289 template<typename... _Args>
291 _M_construct(_Args&&... __args)
292 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
294 ::new (std::__addressof(this->_M_payload))
295 _Stored_type(std::forward<_Args>(__args)...);
296 this->_M_engaged = true;
302 this->_M_engaged = false;
303 this->_M_payload.~_Stored_type();
306 // _M_reset is a 'safe' operation with no precondition.
310 if (this->_M_engaged)
315 struct _Empty_byte { };
317 _Empty_byte _M_empty;
318 _Stored_type _M_payload;
320 bool _M_engaged = false;
323 /// Partial specialization that is exactly identical to the primary template
324 /// save for not providing a destructor, to fulfill triviality requirements.
325 template<typename _Tp>
326 class _Optional_base<_Tp, false>
329 using _Stored_type = typename remove_const<_Tp>::type;
332 constexpr _Optional_base() noexcept
335 constexpr _Optional_base(nullopt_t) noexcept
336 : _Optional_base{} { }
338 constexpr _Optional_base(const _Tp& __t)
339 : _M_payload(__t), _M_engaged(true) { }
341 constexpr _Optional_base(_Tp&& __t)
342 : _M_payload(std::move(__t)), _M_engaged(true) { }
344 template<typename... _Args>
345 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
346 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
348 template<typename _Up, typename... _Args,
349 typename enable_if<is_constructible<_Tp,
350 initializer_list<_Up>&,
353 constexpr explicit _Optional_base(in_place_t,
354 initializer_list<_Up> __il,
356 : _M_payload(__il, std::forward<_Args>(__args)...),
359 _Optional_base(const _Optional_base& __other)
361 if (__other._M_engaged)
362 this->_M_construct(__other._M_get());
365 _Optional_base(_Optional_base&& __other)
366 noexcept(is_nothrow_move_constructible<_Tp>())
368 if (__other._M_engaged)
369 this->_M_construct(std::move(__other._M_get()));
373 operator=(const _Optional_base& __other)
375 if (this->_M_engaged && __other._M_engaged)
376 this->_M_get() = __other._M_get();
379 if (__other._M_engaged)
380 this->_M_construct(__other._M_get());
388 operator=(_Optional_base&& __other)
389 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
390 is_nothrow_move_assignable<_Tp>>())
392 if (this->_M_engaged && __other._M_engaged)
393 this->_M_get() = std::move(__other._M_get());
396 if (__other._M_engaged)
397 this->_M_construct(std::move(__other._M_get()));
405 // ~_Optional_base() noexcept = default;
408 constexpr bool _M_is_engaged() const noexcept
409 { return this->_M_engaged; }
413 { return _M_payload; }
416 _M_get() const noexcept
417 { return _M_payload; }
419 template<typename... _Args>
421 _M_construct(_Args&&... __args)
422 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
424 ::new (std::__addressof(this->_M_payload))
425 _Stored_type(std::forward<_Args>(__args)...);
426 this->_M_engaged = true;
432 this->_M_engaged = false;
433 this->_M_payload.~_Stored_type();
439 if (this->_M_engaged)
444 struct _Empty_byte { };
447 _Empty_byte _M_empty;
448 _Stored_type _M_payload;
450 bool _M_engaged = false;
454 * @brief Class template for optional values.
456 template<typename _Tp>
458 : private _Optional_base<_Tp>,
459 private _Enable_copy_move<
461 is_copy_constructible<_Tp>::value,
463 __and_<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>::value,
465 is_move_constructible<_Tp>::value,
467 __and_<is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value,
471 static_assert(__and_<__not_<is_same<typename remove_cv<_Tp>::type,
473 __not_<is_same<typename remove_cv<_Tp>::type,
475 __not_<is_reference<_Tp>>>(),
476 "Invalid instantiation of optional<T>");
479 using _Base = _Optional_base<_Tp>;
482 using value_type = _Tp;
484 // _Optional_base has the responsibility for construction.
487 // [X.Y.4.3] (partly) Assignment.
489 operator=(nullopt_t) noexcept
495 template<typename _Up>
497 is_same<_Tp, typename decay<_Up>::type>::value,
502 static_assert(__and_<is_constructible<_Tp, _Up>,
503 is_assignable<_Tp&, _Up>>(),
504 "Cannot assign to value type from argument");
506 if (this->_M_is_engaged())
507 this->_M_get() = std::forward<_Up>(__u);
509 this->_M_construct(std::forward<_Up>(__u));
514 template<typename... _Args>
516 emplace(_Args&&... __args)
518 static_assert(is_constructible<_Tp, _Args&&...>(),
519 "Cannot emplace value type from arguments");
522 this->_M_construct(std::forward<_Args>(__args)...);
525 template<typename _Up, typename... _Args>
527 is_constructible<_Tp,
528 initializer_list<_Up>&,
531 emplace(initializer_list<_Up> __il, _Args&&... __args)
534 this->_M_construct(__il, std::forward<_Args>(__args)...);
537 // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base.
541 swap(optional& __other)
542 noexcept(is_nothrow_move_constructible<_Tp>()
543 && noexcept(swap(declval<_Tp&>(), declval<_Tp&>())))
547 if (this->_M_is_engaged() && __other._M_is_engaged())
548 swap(this->_M_get(), __other._M_get());
549 else if (this->_M_is_engaged())
551 __other._M_construct(std::move(this->_M_get()));
554 else if (__other._M_is_engaged())
556 this->_M_construct(std::move(__other._M_get()));
557 __other._M_destruct();
561 // [X.Y.4.5] Observers.
564 { return __constexpr_addressof(this->_M_get()); }
568 { return std::__addressof(this->_M_get()); }
572 { return this->_M_get(); }
576 { return this->_M_get(); }
578 constexpr explicit operator bool() const noexcept
579 { return this->_M_is_engaged(); }
584 return this->_M_is_engaged()
586 : (__throw_bad_optional_access("Attempt to access value of a "
587 "disengaged optional object"),
594 if (this->_M_is_engaged())
595 return this->_M_get();
597 __throw_bad_optional_access("Attempt to access value of a "
598 "disengaged optional object");
601 template<typename _Up>
603 value_or(_Up&& __u) const&
605 static_assert(__and_<is_copy_constructible<_Tp>,
606 is_convertible<_Up&&, _Tp>>(),
607 "Cannot return value");
609 return this->_M_is_engaged()
611 : static_cast<_Tp>(std::forward<_Up>(__u));
614 template<typename _Up>
616 value_or(_Up&& __u) &&
618 static_assert(__and_<is_move_constructible<_Tp>,
619 is_convertible<_Up&&, _Tp>>(),
620 "Cannot return value" );
622 return this->_M_is_engaged()
623 ? std::move(this->_M_get())
624 : static_cast<_Tp>(std::forward<_Up>(__u));
628 // [X.Y.8] Comparisons between optional values.
629 template<typename _Tp>
631 operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
633 return static_cast<bool>(__lhs) == static_cast<bool>(__rhs)
634 && (!__lhs || *__lhs == *__rhs);
637 template<typename _Tp>
639 operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
640 { return !(__lhs == __rhs); }
642 template<typename _Tp>
644 operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
646 return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs);
649 template<typename _Tp>
651 operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
652 { return __rhs < __lhs; }
654 template<typename _Tp>
656 operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
657 { return !(__rhs < __lhs); }
659 template<typename _Tp>
661 operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
662 { return !(__lhs < __rhs); }
664 // [X.Y.9] Comparisons with nullopt.
665 template<typename _Tp>
667 operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept
670 template<typename _Tp>
672 operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept
675 template<typename _Tp>
677 operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept
678 { return static_cast<bool>(__lhs); }
680 template<typename _Tp>
682 operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept
683 { return static_cast<bool>(__rhs); }
685 template<typename _Tp>
687 operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
690 template<typename _Tp>
692 operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept
693 { return static_cast<bool>(__rhs); }
695 template<typename _Tp>
697 operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept
698 { return static_cast<bool>(__lhs); }
700 template<typename _Tp>
702 operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
705 template<typename _Tp>
707 operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept
710 template<typename _Tp>
712 operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
715 template<typename _Tp>
717 operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
720 template<typename _Tp>
722 operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept
725 // [X.Y.10] Comparisons with value type.
726 template<typename _Tp>
728 operator==(const optional<_Tp>& __lhs, const _Tp& __rhs)
729 { return __lhs && *__lhs == __rhs; }
731 template<typename _Tp>
733 operator==(const _Tp& __lhs, const optional<_Tp>& __rhs)
734 { return __rhs && __lhs == *__rhs; }
736 template<typename _Tp>
738 operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs)
739 { return !__lhs || !(*__lhs == __rhs); }
741 template<typename _Tp>
743 operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs)
744 { return !__rhs || !(__lhs == *__rhs); }
746 template<typename _Tp>
748 operator<(const optional<_Tp>& __lhs, const _Tp& __rhs)
749 { return !__lhs || *__lhs < __rhs; }
751 template<typename _Tp>
753 operator<(const _Tp& __lhs, const optional<_Tp>& __rhs)
754 { return __rhs && __lhs < *__rhs; }
756 template<typename _Tp>
758 operator>(const optional<_Tp>& __lhs, const _Tp& __rhs)
759 { return __lhs && __rhs < *__lhs; }
761 template<typename _Tp>
763 operator>(const _Tp& __lhs, const optional<_Tp>& __rhs)
764 { return !__rhs || *__rhs < __lhs; }
766 template<typename _Tp>
768 operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs)
769 { return !__lhs || !(__rhs < *__lhs); }
771 template<typename _Tp>
773 operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs)
774 { return __rhs && !(*__rhs < __lhs); }
776 template<typename _Tp>
778 operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs)
779 { return __lhs && !(*__lhs < __rhs); }
781 template<typename _Tp>
783 operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs)
784 { return !__rhs || !(__lhs < *__rhs); }
787 template<typename _Tp>
789 swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs)
790 noexcept(noexcept(__lhs.swap(__rhs)))
791 { __lhs.swap(__rhs); }
793 template<typename _Tp>
794 constexpr optional<typename decay<_Tp>::type>
795 make_optional(_Tp&& __t)
796 { return optional<typename decay<_Tp>::type> { std::forward<_Tp>(__t) }; }
799 _GLIBCXX_END_NAMESPACE_VERSION
803 template<typename _Tp>
804 struct hash<experimental::optional<_Tp>>
806 using result_type = size_t;
807 using argument_type = experimental::optional<_Tp>;
810 operator()(const experimental::optional<_Tp>& __t) const
811 noexcept(noexcept(hash<_Tp> {}(*__t)))
813 // We pick an arbitrary hash for disengaged optionals which hopefully
814 // usual values of _Tp won't typically hash to.
815 constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333);
816 return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash;
823 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL