1 // <optional> -*- C++ -*-
3 // Copyright (C) 2013-2015 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.
37 * As indicated by the std::experimental namespace and the header paths,
38 * the contents of these Technical Specifications are experimental and not
39 * part of the C++ standard. As such the interfaces and implementations may
40 * change in the future, and there is <STRONG> no guarantee of compatibility
41 * between different GCC releases </STRONG> for these features.
44 #if __cplusplus <= 201103L
45 # include <bits/c++14_warning.h>
49 #include <type_traits>
52 #include <initializer_list>
53 #include <bits/functexcept.h>
54 #include <bits/functional_hash.h>
55 #include <bits/enable_special_members.h>
57 namespace std _GLIBCXX_VISIBILITY(default)
59 namespace experimental
61 inline namespace fundamentals_v1
63 _GLIBCXX_BEGIN_NAMESPACE_VERSION
66 * @defgroup optional Optional values
67 * @ingroup experimental
69 * Class template for optional values and surrounding facilities, as
70 * described in n3793 "A proposal to add a utility class to represent
71 * optional objects (Revision 5)".
76 #define __cpp_lib_experimental_optional 201411
78 // All subsequent [X.Y.n] references are against n3793.
81 template<typename _Tp>
85 /// Tag type for in-place construction.
86 struct in_place_t { };
88 /// Tag for in-place construction.
89 constexpr in_place_t in_place { };
92 /// Tag type to disengage optional objects.
95 // Do not user-declare default constructor at all for
96 // optional_value = {} syntax to work.
97 // nullopt_t() = delete;
99 // Used for constructing nullopt.
100 enum class _Construct { _Token };
102 // Must be constexpr for nullopt_t to be literal.
103 explicit constexpr nullopt_t(_Construct) { }
107 /// Tag to disengage optional objects.
108 constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };
112 * @brief Exception class thrown when a disengaged optional object is
114 * @ingroup exceptions
116 class bad_optional_access : public logic_error
119 bad_optional_access() : logic_error("bad optional access") { }
121 // XXX This constructor is non-standard. Should not be inline
122 explicit bad_optional_access(const char* __arg) : logic_error(__arg) { }
124 virtual ~bad_optional_access() noexcept = default;
128 __throw_bad_optional_access(const char*)
129 __attribute__((__noreturn__));
131 // XXX Does not belong here.
133 __throw_bad_optional_access(const char* __s)
134 { _GLIBCXX_THROW_OR_ABORT(bad_optional_access(__s)); }
136 template<typename _Tp, typename = void>
137 struct _Has_addressof_mem : std::false_type { };
139 template<typename _Tp>
140 struct _Has_addressof_mem<_Tp,
141 __void_t<decltype( std::declval<const _Tp&>().operator&() )>
143 : std::true_type { };
145 template<typename _Tp, typename = void>
146 struct _Has_addressof_free : std::false_type { };
148 template<typename _Tp>
149 struct _Has_addressof_free<_Tp,
150 __void_t<decltype( operator&(std::declval<const _Tp&>()) )>
152 : std::true_type { };
155 * @brief Trait that detects the presence of an overloaded unary operator&.
157 * Practically speaking this detects the presence of such an operator when
158 * called on a const-qualified lvalue (i.e.
159 * declval<_Tp * const&>().operator&()).
161 template<typename _Tp>
162 struct _Has_addressof
163 : std::__or_<_Has_addressof_mem<_Tp>, _Has_addressof_free<_Tp>>::type
167 * @brief An overload that attempts to take the address of an lvalue as a
168 * constant expression. Falls back to __addressof in the presence of an
169 * overloaded addressof operator (unary operator&), in which case the call
170 * will not be a constant expression.
172 template<typename _Tp, enable_if_t<!_Has_addressof<_Tp>::value, int>...>
173 constexpr _Tp* __constexpr_addressof(_Tp& __t)
177 * @brief Fallback overload that defers to __addressof.
179 template<typename _Tp, enable_if_t<_Has_addressof<_Tp>::value, int>...>
180 inline _Tp* __constexpr_addressof(_Tp& __t)
181 { return std::__addressof(__t); }
184 * @brief Class template that holds the necessary state for @ref optional
185 * and that has the responsibility for construction and the special members.
187 * Such a separate base class template is necessary in order to
188 * conditionally enable the special members (e.g. copy/move constructors).
189 * Note that this means that @ref _Optional_base implements the
190 * functionality for copy and move assignment, but not for converting
193 * @see optional, _Enable_special_members
195 template<typename _Tp, bool _ShouldProvideDestructor =
196 !is_trivially_destructible<_Tp>::value>
200 // Remove const to avoid prohibition of reusing object storage for
201 // const-qualified types in [3.8/9]. This is strictly internal
202 // and even optional itself is oblivious to it.
203 using _Stored_type = remove_const_t<_Tp>;
206 // [X.Y.4.1] Constructors.
208 // Constructors for disengaged optionals.
209 constexpr _Optional_base() noexcept
212 constexpr _Optional_base(nullopt_t) noexcept
213 : _Optional_base{} { }
215 // Constructors for engaged optionals.
216 constexpr _Optional_base(const _Tp& __t)
217 : _M_payload(__t), _M_engaged(true) { }
219 constexpr _Optional_base(_Tp&& __t)
220 : _M_payload(std::move(__t)), _M_engaged(true) { }
222 template<typename... _Args>
223 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
224 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
226 template<typename _Up, typename... _Args,
227 enable_if_t<is_constructible<_Tp,
228 initializer_list<_Up>&,
231 constexpr explicit _Optional_base(in_place_t,
232 initializer_list<_Up> __il,
234 : _M_payload(__il, std::forward<_Args>(__args)...),
237 // Copy and move constructors.
238 _Optional_base(const _Optional_base& __other)
240 if (__other._M_engaged)
241 this->_M_construct(__other._M_get());
244 _Optional_base(_Optional_base&& __other)
245 noexcept(is_nothrow_move_constructible<_Tp>())
247 if (__other._M_engaged)
248 this->_M_construct(std::move(__other._M_get()));
251 // [X.Y.4.3] (partly) Assignment.
253 operator=(const _Optional_base& __other)
255 if (this->_M_engaged && __other._M_engaged)
256 this->_M_get() = __other._M_get();
259 if (__other._M_engaged)
260 this->_M_construct(__other._M_get());
269 operator=(_Optional_base&& __other)
270 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
271 is_nothrow_move_assignable<_Tp>>())
273 if (this->_M_engaged && __other._M_engaged)
274 this->_M_get() = std::move(__other._M_get());
277 if (__other._M_engaged)
278 this->_M_construct(std::move(__other._M_get()));
285 // [X.Y.4.2] Destructor.
288 if (this->_M_engaged)
289 this->_M_payload.~_Stored_type();
292 // The following functionality is also needed by optional, hence the
293 // protected accessibility.
295 constexpr bool _M_is_engaged() const noexcept
296 { return this->_M_engaged; }
298 // The _M_get operations have _M_engaged as a precondition.
301 { return _M_payload; }
304 _M_get() const noexcept
305 { return _M_payload; }
307 // The _M_construct operation has !_M_engaged as a precondition
308 // while _M_destruct has _M_engaged as a precondition.
309 template<typename... _Args>
311 _M_construct(_Args&&... __args)
312 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
314 ::new (std::__addressof(this->_M_payload))
315 _Stored_type(std::forward<_Args>(__args)...);
316 this->_M_engaged = true;
322 this->_M_engaged = false;
323 this->_M_payload.~_Stored_type();
326 // _M_reset is a 'safe' operation with no precondition.
330 if (this->_M_engaged)
335 struct _Empty_byte { };
337 _Empty_byte _M_empty;
338 _Stored_type _M_payload;
340 bool _M_engaged = false;
343 /// Partial specialization that is exactly identical to the primary template
344 /// save for not providing a destructor, to fulfill triviality requirements.
345 template<typename _Tp>
346 class _Optional_base<_Tp, false>
349 using _Stored_type = remove_const_t<_Tp>;
352 constexpr _Optional_base() noexcept
355 constexpr _Optional_base(nullopt_t) noexcept
356 : _Optional_base{} { }
358 constexpr _Optional_base(const _Tp& __t)
359 : _M_payload(__t), _M_engaged(true) { }
361 constexpr _Optional_base(_Tp&& __t)
362 : _M_payload(std::move(__t)), _M_engaged(true) { }
364 template<typename... _Args>
365 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
366 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
368 template<typename _Up, typename... _Args,
369 enable_if_t<is_constructible<_Tp,
370 initializer_list<_Up>&,
373 constexpr explicit _Optional_base(in_place_t,
374 initializer_list<_Up> __il,
376 : _M_payload(__il, std::forward<_Args>(__args)...),
379 _Optional_base(const _Optional_base& __other)
381 if (__other._M_engaged)
382 this->_M_construct(__other._M_get());
385 _Optional_base(_Optional_base&& __other)
386 noexcept(is_nothrow_move_constructible<_Tp>())
388 if (__other._M_engaged)
389 this->_M_construct(std::move(__other._M_get()));
393 operator=(const _Optional_base& __other)
395 if (this->_M_engaged && __other._M_engaged)
396 this->_M_get() = __other._M_get();
399 if (__other._M_engaged)
400 this->_M_construct(__other._M_get());
408 operator=(_Optional_base&& __other)
409 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
410 is_nothrow_move_assignable<_Tp>>())
412 if (this->_M_engaged && __other._M_engaged)
413 this->_M_get() = std::move(__other._M_get());
416 if (__other._M_engaged)
417 this->_M_construct(std::move(__other._M_get()));
425 // ~_Optional_base() noexcept = default;
428 constexpr bool _M_is_engaged() const noexcept
429 { return this->_M_engaged; }
433 { return _M_payload; }
436 _M_get() const noexcept
437 { return _M_payload; }
439 template<typename... _Args>
441 _M_construct(_Args&&... __args)
442 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
444 ::new (std::__addressof(this->_M_payload))
445 _Stored_type(std::forward<_Args>(__args)...);
446 this->_M_engaged = true;
452 this->_M_engaged = false;
453 this->_M_payload.~_Stored_type();
459 if (this->_M_engaged)
464 struct _Empty_byte { };
467 _Empty_byte _M_empty;
468 _Stored_type _M_payload;
470 bool _M_engaged = false;
474 * @brief Class template for optional values.
476 template<typename _Tp>
478 : private _Optional_base<_Tp>,
479 private _Enable_copy_move<
481 is_copy_constructible<_Tp>::value,
483 __and_<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>::value,
485 is_move_constructible<_Tp>::value,
487 __and_<is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value,
491 static_assert(__and_<__not_<is_same<remove_cv_t<_Tp>, nullopt_t>>,
492 __not_<is_same<remove_cv_t<_Tp>, in_place_t>>,
493 __not_<is_reference<_Tp>>>(),
494 "Invalid instantiation of optional<T>");
497 using _Base = _Optional_base<_Tp>;
500 using value_type = _Tp;
502 // _Optional_base has the responsibility for construction.
505 // [X.Y.4.3] (partly) Assignment.
507 operator=(nullopt_t) noexcept
513 template<typename _Up>
514 enable_if_t<is_same<_Tp, decay_t<_Up>>::value, optional&>
517 static_assert(__and_<is_constructible<_Tp, _Up>,
518 is_assignable<_Tp&, _Up>>(),
519 "Cannot assign to value type from argument");
521 if (this->_M_is_engaged())
522 this->_M_get() = std::forward<_Up>(__u);
524 this->_M_construct(std::forward<_Up>(__u));
529 template<typename... _Args>
531 emplace(_Args&&... __args)
533 static_assert(is_constructible<_Tp, _Args&&...>(),
534 "Cannot emplace value type from arguments");
537 this->_M_construct(std::forward<_Args>(__args)...);
540 template<typename _Up, typename... _Args>
541 enable_if_t<is_constructible<_Tp, initializer_list<_Up>&,
543 emplace(initializer_list<_Up> __il, _Args&&... __args)
546 this->_M_construct(__il, std::forward<_Args>(__args)...);
549 // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base.
553 swap(optional& __other)
554 noexcept(is_nothrow_move_constructible<_Tp>()
555 && noexcept(swap(declval<_Tp&>(), declval<_Tp&>())))
559 if (this->_M_is_engaged() && __other._M_is_engaged())
560 swap(this->_M_get(), __other._M_get());
561 else if (this->_M_is_engaged())
563 __other._M_construct(std::move(this->_M_get()));
566 else if (__other._M_is_engaged())
568 this->_M_construct(std::move(__other._M_get()));
569 __other._M_destruct();
573 // [X.Y.4.5] Observers.
576 { return __constexpr_addressof(this->_M_get()); }
580 { return std::__addressof(this->_M_get()); }
584 { return this->_M_get(); }
588 { return this->_M_get(); }
592 { return std::move(this->_M_get()); }
594 constexpr const _Tp&&
596 { return std::move(this->_M_get()); }
598 constexpr explicit operator bool() const noexcept
599 { return this->_M_is_engaged(); }
604 return this->_M_is_engaged()
606 : (__throw_bad_optional_access("Attempt to access value of a "
607 "disengaged optional object"),
614 return this->_M_is_engaged()
616 : (__throw_bad_optional_access("Attempt to access value of a "
617 "disengaged optional object"),
624 return this->_M_is_engaged()
625 ? std::move(this->_M_get())
626 : (__throw_bad_optional_access("Attempt to access value of a "
627 "disengaged optional object"),
628 std::move(this->_M_get()));
631 constexpr const _Tp&&
634 return this->_M_is_engaged()
635 ? std::move(this->_M_get())
636 : (__throw_bad_optional_access("Attempt to access value of a "
637 "disengaged optional object"),
638 std::move(this->_M_get()));
641 template<typename _Up>
643 value_or(_Up&& __u) const&
645 static_assert(__and_<is_copy_constructible<_Tp>,
646 is_convertible<_Up&&, _Tp>>(),
647 "Cannot return value");
649 return this->_M_is_engaged()
651 : static_cast<_Tp>(std::forward<_Up>(__u));
654 template<typename _Up>
656 value_or(_Up&& __u) &&
658 static_assert(__and_<is_move_constructible<_Tp>,
659 is_convertible<_Up&&, _Tp>>(),
660 "Cannot return value" );
662 return this->_M_is_engaged()
663 ? std::move(this->_M_get())
664 : static_cast<_Tp>(std::forward<_Up>(__u));
668 // [X.Y.8] Comparisons between optional values.
669 template<typename _Tp>
671 operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
673 return static_cast<bool>(__lhs) == static_cast<bool>(__rhs)
674 && (!__lhs || *__lhs == *__rhs);
677 template<typename _Tp>
679 operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
680 { return !(__lhs == __rhs); }
682 template<typename _Tp>
684 operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
686 return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs);
689 template<typename _Tp>
691 operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
692 { return __rhs < __lhs; }
694 template<typename _Tp>
696 operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
697 { return !(__rhs < __lhs); }
699 template<typename _Tp>
701 operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
702 { return !(__lhs < __rhs); }
704 // [X.Y.9] Comparisons with nullopt.
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
718 { return static_cast<bool>(__lhs); }
720 template<typename _Tp>
722 operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept
723 { return static_cast<bool>(__rhs); }
725 template<typename _Tp>
727 operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
730 template<typename _Tp>
732 operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept
733 { return static_cast<bool>(__rhs); }
735 template<typename _Tp>
737 operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept
738 { return static_cast<bool>(__lhs); }
740 template<typename _Tp>
742 operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
745 template<typename _Tp>
747 operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept
750 template<typename _Tp>
752 operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
755 template<typename _Tp>
757 operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
760 template<typename _Tp>
762 operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept
765 // [X.Y.10] Comparisons with value type.
766 template<typename _Tp>
768 operator==(const optional<_Tp>& __lhs, const _Tp& __rhs)
769 { return __lhs && *__lhs == __rhs; }
771 template<typename _Tp>
773 operator==(const _Tp& __lhs, const optional<_Tp>& __rhs)
774 { return __rhs && __lhs == *__rhs; }
776 template<typename _Tp>
778 operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs)
779 { return !__lhs || !(*__lhs == __rhs); }
781 template<typename _Tp>
783 operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs)
784 { return !__rhs || !(__lhs == *__rhs); }
786 template<typename _Tp>
788 operator<(const optional<_Tp>& __lhs, const _Tp& __rhs)
789 { return !__lhs || *__lhs < __rhs; }
791 template<typename _Tp>
793 operator<(const _Tp& __lhs, const optional<_Tp>& __rhs)
794 { return __rhs && __lhs < *__rhs; }
796 template<typename _Tp>
798 operator>(const optional<_Tp>& __lhs, const _Tp& __rhs)
799 { return __lhs && __rhs < *__lhs; }
801 template<typename _Tp>
803 operator>(const _Tp& __lhs, const optional<_Tp>& __rhs)
804 { return !__rhs || *__rhs < __lhs; }
806 template<typename _Tp>
808 operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs)
809 { return !__lhs || !(__rhs < *__lhs); }
811 template<typename _Tp>
813 operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs)
814 { return __rhs && !(*__rhs < __lhs); }
816 template<typename _Tp>
818 operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs)
819 { return __lhs && !(*__lhs < __rhs); }
821 template<typename _Tp>
823 operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs)
824 { return !__rhs || !(__lhs < *__rhs); }
827 template<typename _Tp>
829 swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs)
830 noexcept(noexcept(__lhs.swap(__rhs)))
831 { __lhs.swap(__rhs); }
833 template<typename _Tp>
834 constexpr optional<decay_t<_Tp>>
835 make_optional(_Tp&& __t)
836 { return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; }
839 _GLIBCXX_END_NAMESPACE_VERSION
840 } // namespace fundamentals_v1
844 template<typename _Tp>
845 struct hash<experimental::optional<_Tp>>
847 using result_type = size_t;
848 using argument_type = experimental::optional<_Tp>;
851 operator()(const experimental::optional<_Tp>& __t) const
852 noexcept(noexcept(hash<_Tp> {}(*__t)))
854 // We pick an arbitrary hash for disengaged optionals which hopefully
855 // usual values of _Tp won't typically hash to.
856 constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333);
857 return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash;
864 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL