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>
56 #include <experimental/lfts_config.h>
58 namespace std _GLIBCXX_VISIBILITY(default)
60 namespace experimental
62 inline namespace fundamentals_v1
64 _GLIBCXX_BEGIN_NAMESPACE_VERSION
67 * @defgroup optional Optional values
68 * @ingroup experimental
70 * Class template for optional values and surrounding facilities, as
71 * described in n3793 "A proposal to add a utility class to represent
72 * optional objects (Revision 5)".
77 #define __cpp_lib_experimental_optional 201411
79 // All subsequent [X.Y.n] references are against n3793.
82 template<typename _Tp>
86 /// Tag type for in-place construction.
87 struct in_place_t { };
89 /// Tag for in-place construction.
90 constexpr in_place_t in_place { };
93 /// Tag type to disengage optional objects.
96 // Do not user-declare default constructor at all for
97 // optional_value = {} syntax to work.
98 // nullopt_t() = delete;
100 // Used for constructing nullopt.
101 enum class _Construct { _Token };
103 // Must be constexpr for nullopt_t to be literal.
104 explicit constexpr nullopt_t(_Construct) { }
108 /// Tag to disengage optional objects.
109 constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };
113 * @brief Exception class thrown when a disengaged optional object is
115 * @ingroup exceptions
117 class bad_optional_access : public logic_error
120 bad_optional_access() : logic_error("bad optional access") { }
122 // XXX This constructor is non-standard. Should not be inline
123 explicit bad_optional_access(const char* __arg) : logic_error(__arg) { }
125 virtual ~bad_optional_access() noexcept = default;
129 __throw_bad_optional_access(const char*)
130 __attribute__((__noreturn__));
132 // XXX Does not belong here.
134 __throw_bad_optional_access(const char* __s)
135 { _GLIBCXX_THROW_OR_ABORT(bad_optional_access(__s)); }
137 #ifndef __cpp_lib_addressof_constexpr
138 template<typename _Tp, typename = void>
139 struct _Has_addressof_mem : std::false_type { };
141 template<typename _Tp>
142 struct _Has_addressof_mem<_Tp,
143 __void_t<decltype( std::declval<const _Tp&>().operator&() )>
145 : std::true_type { };
147 template<typename _Tp, typename = void>
148 struct _Has_addressof_free : std::false_type { };
150 template<typename _Tp>
151 struct _Has_addressof_free<_Tp,
152 __void_t<decltype( operator&(std::declval<const _Tp&>()) )>
154 : std::true_type { };
157 * @brief Trait that detects the presence of an overloaded unary operator&.
159 * Practically speaking this detects the presence of such an operator when
160 * called on a const-qualified lvalue (i.e.
161 * declval<_Tp * const&>().operator&()).
163 template<typename _Tp>
164 struct _Has_addressof
165 : std::__or_<_Has_addressof_mem<_Tp>, _Has_addressof_free<_Tp>>::type
169 * @brief An overload that attempts to take the address of an lvalue as a
170 * constant expression. Falls back to __addressof in the presence of an
171 * overloaded addressof operator (unary operator&), in which case the call
172 * will not be a constant expression.
174 template<typename _Tp>
176 enable_if_t<!_Has_addressof<_Tp>::value, _Tp*>
177 __constexpr_addressof(_Tp& __t)
181 * @brief Fallback overload that defers to __addressof.
183 template<typename _Tp>
185 enable_if_t<_Has_addressof<_Tp>::value, _Tp*>
186 __constexpr_addressof(_Tp& __t)
187 { return std::__addressof(__t); }
188 #endif // __cpp_lib_addressof_constexpr
191 * @brief Class template that holds the necessary state for @ref optional
192 * and that has the responsibility for construction and the special members.
194 * Such a separate base class template is necessary in order to
195 * conditionally enable the special members (e.g. copy/move constructors).
196 * Note that this means that @ref _Optional_base implements the
197 * functionality for copy and move assignment, but not for converting
200 * @see optional, _Enable_special_members
202 template<typename _Tp, bool _ShouldProvideDestructor =
203 !is_trivially_destructible<_Tp>::value>
207 // Remove const to avoid prohibition of reusing object storage for
208 // const-qualified types in [3.8/9]. This is strictly internal
209 // and even optional itself is oblivious to it.
210 using _Stored_type = remove_const_t<_Tp>;
213 // [X.Y.4.1] Constructors.
215 // Constructors for disengaged optionals.
216 constexpr _Optional_base() noexcept
219 constexpr _Optional_base(nullopt_t) noexcept
220 : _Optional_base{} { }
222 // Constructors for engaged optionals.
223 constexpr _Optional_base(const _Tp& __t)
224 : _M_payload(__t), _M_engaged(true) { }
226 constexpr _Optional_base(_Tp&& __t)
227 : _M_payload(std::move(__t)), _M_engaged(true) { }
229 template<typename... _Args>
230 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
231 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
233 template<typename _Up, typename... _Args,
234 enable_if_t<is_constructible<_Tp,
235 initializer_list<_Up>&,
238 constexpr explicit _Optional_base(in_place_t,
239 initializer_list<_Up> __il,
241 : _M_payload(__il, std::forward<_Args>(__args)...),
244 // Copy and move constructors.
245 _Optional_base(const _Optional_base& __other)
247 if (__other._M_engaged)
248 this->_M_construct(__other._M_get());
251 _Optional_base(_Optional_base&& __other)
252 noexcept(is_nothrow_move_constructible<_Tp>())
254 if (__other._M_engaged)
255 this->_M_construct(std::move(__other._M_get()));
258 // [X.Y.4.3] (partly) Assignment.
260 operator=(const _Optional_base& __other)
262 if (this->_M_engaged && __other._M_engaged)
263 this->_M_get() = __other._M_get();
266 if (__other._M_engaged)
267 this->_M_construct(__other._M_get());
276 operator=(_Optional_base&& __other)
277 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
278 is_nothrow_move_assignable<_Tp>>())
280 if (this->_M_engaged && __other._M_engaged)
281 this->_M_get() = std::move(__other._M_get());
284 if (__other._M_engaged)
285 this->_M_construct(std::move(__other._M_get()));
292 // [X.Y.4.2] Destructor.
295 if (this->_M_engaged)
296 this->_M_payload.~_Stored_type();
299 // The following functionality is also needed by optional, hence the
300 // protected accessibility.
302 constexpr bool _M_is_engaged() const noexcept
303 { return this->_M_engaged; }
305 // The _M_get operations have _M_engaged as a precondition.
308 { return _M_payload; }
311 _M_get() const noexcept
312 { return _M_payload; }
314 // The _M_construct operation has !_M_engaged as a precondition
315 // while _M_destruct has _M_engaged as a precondition.
316 template<typename... _Args>
318 _M_construct(_Args&&... __args)
319 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
321 ::new (std::__addressof(this->_M_payload))
322 _Stored_type(std::forward<_Args>(__args)...);
323 this->_M_engaged = true;
329 this->_M_engaged = false;
330 this->_M_payload.~_Stored_type();
333 // _M_reset is a 'safe' operation with no precondition.
337 if (this->_M_engaged)
342 struct _Empty_byte { };
344 _Empty_byte _M_empty;
345 _Stored_type _M_payload;
347 bool _M_engaged = false;
350 /// Partial specialization that is exactly identical to the primary template
351 /// save for not providing a destructor, to fulfill triviality requirements.
352 template<typename _Tp>
353 class _Optional_base<_Tp, false>
356 using _Stored_type = remove_const_t<_Tp>;
359 constexpr _Optional_base() noexcept
362 constexpr _Optional_base(nullopt_t) noexcept
363 : _Optional_base{} { }
365 constexpr _Optional_base(const _Tp& __t)
366 : _M_payload(__t), _M_engaged(true) { }
368 constexpr _Optional_base(_Tp&& __t)
369 : _M_payload(std::move(__t)), _M_engaged(true) { }
371 template<typename... _Args>
372 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
373 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
375 template<typename _Up, typename... _Args,
376 enable_if_t<is_constructible<_Tp,
377 initializer_list<_Up>&,
380 constexpr explicit _Optional_base(in_place_t,
381 initializer_list<_Up> __il,
383 : _M_payload(__il, std::forward<_Args>(__args)...),
386 _Optional_base(const _Optional_base& __other)
388 if (__other._M_engaged)
389 this->_M_construct(__other._M_get());
392 _Optional_base(_Optional_base&& __other)
393 noexcept(is_nothrow_move_constructible<_Tp>())
395 if (__other._M_engaged)
396 this->_M_construct(std::move(__other._M_get()));
400 operator=(const _Optional_base& __other)
402 if (this->_M_engaged && __other._M_engaged)
403 this->_M_get() = __other._M_get();
406 if (__other._M_engaged)
407 this->_M_construct(__other._M_get());
415 operator=(_Optional_base&& __other)
416 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
417 is_nothrow_move_assignable<_Tp>>())
419 if (this->_M_engaged && __other._M_engaged)
420 this->_M_get() = std::move(__other._M_get());
423 if (__other._M_engaged)
424 this->_M_construct(std::move(__other._M_get()));
432 // ~_Optional_base() noexcept = default;
435 constexpr bool _M_is_engaged() const noexcept
436 { return this->_M_engaged; }
440 { return _M_payload; }
443 _M_get() const noexcept
444 { return _M_payload; }
446 template<typename... _Args>
448 _M_construct(_Args&&... __args)
449 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
451 ::new (std::__addressof(this->_M_payload))
452 _Stored_type(std::forward<_Args>(__args)...);
453 this->_M_engaged = true;
459 this->_M_engaged = false;
460 this->_M_payload.~_Stored_type();
466 if (this->_M_engaged)
471 struct _Empty_byte { };
474 _Empty_byte _M_empty;
475 _Stored_type _M_payload;
477 bool _M_engaged = false;
481 * @brief Class template for optional values.
483 template<typename _Tp>
485 : private _Optional_base<_Tp>,
486 private _Enable_copy_move<
488 is_copy_constructible<_Tp>::value,
490 __and_<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>::value,
492 is_move_constructible<_Tp>::value,
494 __and_<is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value,
498 static_assert(__and_<__not_<is_same<remove_cv_t<_Tp>, nullopt_t>>,
499 __not_<is_same<remove_cv_t<_Tp>, in_place_t>>,
500 __not_<is_reference<_Tp>>>(),
501 "Invalid instantiation of optional<T>");
504 using _Base = _Optional_base<_Tp>;
507 using value_type = _Tp;
509 // _Optional_base has the responsibility for construction.
512 // [X.Y.4.3] (partly) Assignment.
514 operator=(nullopt_t) noexcept
520 template<typename _Up>
521 enable_if_t<is_same<_Tp, decay_t<_Up>>::value, optional&>
524 static_assert(__and_<is_constructible<_Tp, _Up>,
525 is_assignable<_Tp&, _Up>>(),
526 "Cannot assign to value type from argument");
528 if (this->_M_is_engaged())
529 this->_M_get() = std::forward<_Up>(__u);
531 this->_M_construct(std::forward<_Up>(__u));
536 template<typename... _Args>
538 emplace(_Args&&... __args)
540 static_assert(is_constructible<_Tp, _Args&&...>(),
541 "Cannot emplace value type from arguments");
544 this->_M_construct(std::forward<_Args>(__args)...);
547 template<typename _Up, typename... _Args>
548 enable_if_t<is_constructible<_Tp, initializer_list<_Up>&,
550 emplace(initializer_list<_Up> __il, _Args&&... __args)
553 this->_M_construct(__il, std::forward<_Args>(__args)...);
556 // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base.
560 swap(optional& __other)
561 noexcept(is_nothrow_move_constructible<_Tp>()
562 && noexcept(swap(declval<_Tp&>(), declval<_Tp&>())))
566 if (this->_M_is_engaged() && __other._M_is_engaged())
567 swap(this->_M_get(), __other._M_get());
568 else if (this->_M_is_engaged())
570 __other._M_construct(std::move(this->_M_get()));
573 else if (__other._M_is_engaged())
575 this->_M_construct(std::move(__other._M_get()));
576 __other._M_destruct();
580 // [X.Y.4.5] Observers.
584 #ifndef __cpp_lib_addressof_constexpr
585 return __constexpr_addressof(this->_M_get());
587 return std::__addressof(this->_M_get());
593 { return std::__addressof(this->_M_get()); }
597 { return this->_M_get(); }
601 { return this->_M_get(); }
605 { return std::move(this->_M_get()); }
607 constexpr const _Tp&&
609 { return std::move(this->_M_get()); }
611 constexpr explicit operator bool() const noexcept
612 { return this->_M_is_engaged(); }
617 return this->_M_is_engaged()
619 : (__throw_bad_optional_access("Attempt to access value of a "
620 "disengaged optional object"),
627 return this->_M_is_engaged()
629 : (__throw_bad_optional_access("Attempt to access value of a "
630 "disengaged optional object"),
637 return this->_M_is_engaged()
638 ? std::move(this->_M_get())
639 : (__throw_bad_optional_access("Attempt to access value of a "
640 "disengaged optional object"),
641 std::move(this->_M_get()));
644 constexpr const _Tp&&
647 return this->_M_is_engaged()
648 ? std::move(this->_M_get())
649 : (__throw_bad_optional_access("Attempt to access value of a "
650 "disengaged optional object"),
651 std::move(this->_M_get()));
654 template<typename _Up>
656 value_or(_Up&& __u) const&
658 static_assert(__and_<is_copy_constructible<_Tp>,
659 is_convertible<_Up&&, _Tp>>(),
660 "Cannot return value");
662 return this->_M_is_engaged()
664 : static_cast<_Tp>(std::forward<_Up>(__u));
667 template<typename _Up>
669 value_or(_Up&& __u) &&
671 static_assert(__and_<is_move_constructible<_Tp>,
672 is_convertible<_Up&&, _Tp>>(),
673 "Cannot return value" );
675 return this->_M_is_engaged()
676 ? std::move(this->_M_get())
677 : static_cast<_Tp>(std::forward<_Up>(__u));
681 // [X.Y.8] Comparisons between optional values.
682 template<typename _Tp>
684 operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
686 return static_cast<bool>(__lhs) == static_cast<bool>(__rhs)
687 && (!__lhs || *__lhs == *__rhs);
690 template<typename _Tp>
692 operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
693 { return !(__lhs == __rhs); }
695 template<typename _Tp>
697 operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
699 return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs);
702 template<typename _Tp>
704 operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
705 { return __rhs < __lhs; }
707 template<typename _Tp>
709 operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
710 { return !(__rhs < __lhs); }
712 template<typename _Tp>
714 operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
715 { return !(__lhs < __rhs); }
717 // [X.Y.9] Comparisons with nullopt.
718 template<typename _Tp>
720 operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept
723 template<typename _Tp>
725 operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept
728 template<typename _Tp>
730 operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept
731 { return static_cast<bool>(__lhs); }
733 template<typename _Tp>
735 operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept
736 { return static_cast<bool>(__rhs); }
738 template<typename _Tp>
740 operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
743 template<typename _Tp>
745 operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept
746 { return static_cast<bool>(__rhs); }
748 template<typename _Tp>
750 operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept
751 { return static_cast<bool>(__lhs); }
753 template<typename _Tp>
755 operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
758 template<typename _Tp>
760 operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept
763 template<typename _Tp>
765 operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
768 template<typename _Tp>
770 operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
773 template<typename _Tp>
775 operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept
778 // [X.Y.10] Comparisons with value type.
779 template<typename _Tp>
781 operator==(const optional<_Tp>& __lhs, const _Tp& __rhs)
782 { return __lhs && *__lhs == __rhs; }
784 template<typename _Tp>
786 operator==(const _Tp& __lhs, const optional<_Tp>& __rhs)
787 { return __rhs && __lhs == *__rhs; }
789 template<typename _Tp>
791 operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs)
792 { return !__lhs || !(*__lhs == __rhs); }
794 template<typename _Tp>
796 operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs)
797 { return !__rhs || !(__lhs == *__rhs); }
799 template<typename _Tp>
801 operator<(const optional<_Tp>& __lhs, const _Tp& __rhs)
802 { return !__lhs || *__lhs < __rhs; }
804 template<typename _Tp>
806 operator<(const _Tp& __lhs, const optional<_Tp>& __rhs)
807 { return __rhs && __lhs < *__rhs; }
809 template<typename _Tp>
811 operator>(const optional<_Tp>& __lhs, const _Tp& __rhs)
812 { return __lhs && __rhs < *__lhs; }
814 template<typename _Tp>
816 operator>(const _Tp& __lhs, const optional<_Tp>& __rhs)
817 { return !__rhs || *__rhs < __lhs; }
819 template<typename _Tp>
821 operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs)
822 { return !__lhs || !(__rhs < *__lhs); }
824 template<typename _Tp>
826 operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs)
827 { return __rhs && !(*__rhs < __lhs); }
829 template<typename _Tp>
831 operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs)
832 { return __lhs && !(*__lhs < __rhs); }
834 template<typename _Tp>
836 operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs)
837 { return !__rhs || !(__lhs < *__rhs); }
840 template<typename _Tp>
842 swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs)
843 noexcept(noexcept(__lhs.swap(__rhs)))
844 { __lhs.swap(__rhs); }
846 template<typename _Tp>
847 constexpr optional<decay_t<_Tp>>
848 make_optional(_Tp&& __t)
849 { return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; }
852 _GLIBCXX_END_NAMESPACE_VERSION
853 } // namespace fundamentals_v1
857 template<typename _Tp>
858 struct hash<experimental::optional<_Tp>>
860 using result_type = size_t;
861 using argument_type = experimental::optional<_Tp>;
864 operator()(const experimental::optional<_Tp>& __t) const
865 noexcept(noexcept(hash<_Tp> {}(*__t)))
867 // We pick an arbitrary hash for disengaged optionals which hopefully
868 // usual values of _Tp won't typically hash to.
869 constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333);
870 return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash;
877 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL