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.
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 inline namespace fundamentals_v1
57 _GLIBCXX_BEGIN_NAMESPACE_VERSION
60 * @defgroup optional Optional values
61 * @ingroup experimental
63 * Class template for optional values and surrounding facilities, as
64 * described in n3793 "A proposal to add a utility class to represent
65 * optional objects (Revision 5)".
70 #define __cpp_lib_experimental_optional 201411
72 // All subsequent [X.Y.n] references are against n3793.
75 template<typename _Tp>
79 /// Tag type for in-place construction.
80 struct in_place_t { };
82 /// Tag for in-place construction.
83 constexpr in_place_t in_place { };
86 /// Tag type to disengage optional objects.
89 // Do not user-declare default constructor at all for
90 // optional_value = {} syntax to work.
91 // nullopt_t() = delete;
93 // Used for constructing nullopt.
94 enum class _Construct { _Token };
96 // Must be constexpr for nullopt_t to be literal.
97 explicit constexpr nullopt_t(_Construct) { }
101 /// Tag to disengage optional objects.
102 constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };
106 * @brief Exception class thrown when a disengaged optional object is
108 * @ingroup exceptions
110 class bad_optional_access : public logic_error
113 bad_optional_access() : logic_error("bad optional access") { }
115 // XXX This constructor is non-standard. Should not be inline
116 explicit bad_optional_access(const char* __arg) : logic_error(__arg) { }
118 virtual ~bad_optional_access() noexcept = default;
122 __throw_bad_optional_access(const char*)
123 __attribute__((__noreturn__));
125 // XXX Does not belong here.
127 __throw_bad_optional_access(const char* __s)
128 { _GLIBCXX_THROW_OR_ABORT(bad_optional_access(__s)); }
130 template<typename _Tp, typename = void>
131 struct _Has_addressof_mem : std::false_type { };
133 template<typename _Tp>
134 struct _Has_addressof_mem<_Tp,
135 __void_t<decltype( std::declval<const _Tp&>().operator&() )>
137 : std::true_type { };
139 template<typename _Tp, typename = void>
140 struct _Has_addressof_free : std::false_type { };
142 template<typename _Tp>
143 struct _Has_addressof_free<_Tp,
144 __void_t<decltype( operator&(std::declval<const _Tp&>()) )>
146 : std::true_type { };
149 * @brief Trait that detects the presence of an overloaded unary operator&.
151 * Practically speaking this detects the presence of such an operator when
152 * called on a const-qualified lvalue (i.e.
153 * declval<_Tp * const&>().operator&()).
155 template<typename _Tp>
156 struct _Has_addressof
157 : std::__or_<_Has_addressof_mem<_Tp>, _Has_addressof_free<_Tp>>::type
161 * @brief An overload that attempts to take the address of an lvalue as a
162 * constant expression. Falls back to __addressof in the presence of an
163 * overloaded addressof operator (unary operator&), in which case the call
164 * will not be a constant expression.
166 template<typename _Tp, enable_if_t<!_Has_addressof<_Tp>::value, int>...>
167 constexpr _Tp* __constexpr_addressof(_Tp& __t)
171 * @brief Fallback overload that defers to __addressof.
173 template<typename _Tp, enable_if_t<_Has_addressof<_Tp>::value, int>...>
174 inline _Tp* __constexpr_addressof(_Tp& __t)
175 { return std::__addressof(__t); }
178 * @brief Class template that holds the necessary state for @ref optional
179 * and that has the responsibility for construction and the special members.
181 * Such a separate base class template is necessary in order to
182 * conditionally enable the special members (e.g. copy/move constructors).
183 * Note that this means that @ref _Optional_base implements the
184 * functionality for copy and move assignment, but not for converting
187 * @see optional, _Enable_special_members
189 template<typename _Tp, bool _ShouldProvideDestructor =
190 !is_trivially_destructible<_Tp>::value>
194 // Remove const to avoid prohibition of reusing object storage for
195 // const-qualified types in [3.8/9]. This is strictly internal
196 // and even optional itself is oblivious to it.
197 using _Stored_type = remove_const_t<_Tp>;
200 // [X.Y.4.1] Constructors.
202 // Constructors for disengaged optionals.
203 constexpr _Optional_base() noexcept
206 constexpr _Optional_base(nullopt_t) noexcept
207 : _Optional_base{} { }
209 // Constructors for engaged optionals.
210 constexpr _Optional_base(const _Tp& __t)
211 : _M_payload(__t), _M_engaged(true) { }
213 constexpr _Optional_base(_Tp&& __t)
214 : _M_payload(std::move(__t)), _M_engaged(true) { }
216 template<typename... _Args>
217 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
218 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
220 template<typename _Up, typename... _Args,
221 enable_if_t<is_constructible<_Tp,
222 initializer_list<_Up>&,
225 constexpr explicit _Optional_base(in_place_t,
226 initializer_list<_Up> __il,
228 : _M_payload(__il, std::forward<_Args>(__args)...),
231 // Copy and move constructors.
232 _Optional_base(const _Optional_base& __other)
234 if (__other._M_engaged)
235 this->_M_construct(__other._M_get());
238 _Optional_base(_Optional_base&& __other)
239 noexcept(is_nothrow_move_constructible<_Tp>())
241 if (__other._M_engaged)
242 this->_M_construct(std::move(__other._M_get()));
245 // [X.Y.4.3] (partly) Assignment.
247 operator=(const _Optional_base& __other)
249 if (this->_M_engaged && __other._M_engaged)
250 this->_M_get() = __other._M_get();
253 if (__other._M_engaged)
254 this->_M_construct(__other._M_get());
263 operator=(_Optional_base&& __other)
264 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
265 is_nothrow_move_assignable<_Tp>>())
267 if (this->_M_engaged && __other._M_engaged)
268 this->_M_get() = std::move(__other._M_get());
271 if (__other._M_engaged)
272 this->_M_construct(std::move(__other._M_get()));
279 // [X.Y.4.2] Destructor.
282 if (this->_M_engaged)
283 this->_M_payload.~_Stored_type();
286 // The following functionality is also needed by optional, hence the
287 // protected accessibility.
289 constexpr bool _M_is_engaged() const noexcept
290 { return this->_M_engaged; }
292 // The _M_get operations have _M_engaged as a precondition.
295 { return _M_payload; }
298 _M_get() const noexcept
299 { return _M_payload; }
301 // The _M_construct operation has !_M_engaged as a precondition
302 // while _M_destruct has _M_engaged as a precondition.
303 template<typename... _Args>
305 _M_construct(_Args&&... __args)
306 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
308 ::new (std::__addressof(this->_M_payload))
309 _Stored_type(std::forward<_Args>(__args)...);
310 this->_M_engaged = true;
316 this->_M_engaged = false;
317 this->_M_payload.~_Stored_type();
320 // _M_reset is a 'safe' operation with no precondition.
324 if (this->_M_engaged)
329 struct _Empty_byte { };
331 _Empty_byte _M_empty;
332 _Stored_type _M_payload;
334 bool _M_engaged = false;
337 /// Partial specialization that is exactly identical to the primary template
338 /// save for not providing a destructor, to fulfill triviality requirements.
339 template<typename _Tp>
340 class _Optional_base<_Tp, false>
343 using _Stored_type = remove_const_t<_Tp>;
346 constexpr _Optional_base() noexcept
349 constexpr _Optional_base(nullopt_t) noexcept
350 : _Optional_base{} { }
352 constexpr _Optional_base(const _Tp& __t)
353 : _M_payload(__t), _M_engaged(true) { }
355 constexpr _Optional_base(_Tp&& __t)
356 : _M_payload(std::move(__t)), _M_engaged(true) { }
358 template<typename... _Args>
359 constexpr explicit _Optional_base(in_place_t, _Args&&... __args)
360 : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { }
362 template<typename _Up, typename... _Args,
363 enable_if_t<is_constructible<_Tp,
364 initializer_list<_Up>&,
367 constexpr explicit _Optional_base(in_place_t,
368 initializer_list<_Up> __il,
370 : _M_payload(__il, std::forward<_Args>(__args)...),
373 _Optional_base(const _Optional_base& __other)
375 if (__other._M_engaged)
376 this->_M_construct(__other._M_get());
379 _Optional_base(_Optional_base&& __other)
380 noexcept(is_nothrow_move_constructible<_Tp>())
382 if (__other._M_engaged)
383 this->_M_construct(std::move(__other._M_get()));
387 operator=(const _Optional_base& __other)
389 if (this->_M_engaged && __other._M_engaged)
390 this->_M_get() = __other._M_get();
393 if (__other._M_engaged)
394 this->_M_construct(__other._M_get());
402 operator=(_Optional_base&& __other)
403 noexcept(__and_<is_nothrow_move_constructible<_Tp>,
404 is_nothrow_move_assignable<_Tp>>())
406 if (this->_M_engaged && __other._M_engaged)
407 this->_M_get() = std::move(__other._M_get());
410 if (__other._M_engaged)
411 this->_M_construct(std::move(__other._M_get()));
419 // ~_Optional_base() noexcept = default;
422 constexpr bool _M_is_engaged() const noexcept
423 { return this->_M_engaged; }
427 { return _M_payload; }
430 _M_get() const noexcept
431 { return _M_payload; }
433 template<typename... _Args>
435 _M_construct(_Args&&... __args)
436 noexcept(is_nothrow_constructible<_Stored_type, _Args...>())
438 ::new (std::__addressof(this->_M_payload))
439 _Stored_type(std::forward<_Args>(__args)...);
440 this->_M_engaged = true;
446 this->_M_engaged = false;
447 this->_M_payload.~_Stored_type();
453 if (this->_M_engaged)
458 struct _Empty_byte { };
461 _Empty_byte _M_empty;
462 _Stored_type _M_payload;
464 bool _M_engaged = false;
468 * @brief Class template for optional values.
470 template<typename _Tp>
472 : private _Optional_base<_Tp>,
473 private _Enable_copy_move<
475 is_copy_constructible<_Tp>::value,
477 __and_<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>::value,
479 is_move_constructible<_Tp>::value,
481 __and_<is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value,
485 static_assert(__and_<__not_<is_same<remove_cv_t<_Tp>, nullopt_t>>,
486 __not_<is_same<remove_cv_t<_Tp>, in_place_t>>,
487 __not_<is_reference<_Tp>>>(),
488 "Invalid instantiation of optional<T>");
491 using _Base = _Optional_base<_Tp>;
494 using value_type = _Tp;
496 // _Optional_base has the responsibility for construction.
499 // [X.Y.4.3] (partly) Assignment.
501 operator=(nullopt_t) noexcept
507 template<typename _Up>
508 enable_if_t<is_same<_Tp, decay_t<_Up>>::value, optional&>
511 static_assert(__and_<is_constructible<_Tp, _Up>,
512 is_assignable<_Tp&, _Up>>(),
513 "Cannot assign to value type from argument");
515 if (this->_M_is_engaged())
516 this->_M_get() = std::forward<_Up>(__u);
518 this->_M_construct(std::forward<_Up>(__u));
523 template<typename... _Args>
525 emplace(_Args&&... __args)
527 static_assert(is_constructible<_Tp, _Args&&...>(),
528 "Cannot emplace value type from arguments");
531 this->_M_construct(std::forward<_Args>(__args)...);
534 template<typename _Up, typename... _Args>
535 enable_if_t<is_constructible<_Tp, initializer_list<_Up>&,
537 emplace(initializer_list<_Up> __il, _Args&&... __args)
540 this->_M_construct(__il, std::forward<_Args>(__args)...);
543 // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base.
547 swap(optional& __other)
548 noexcept(is_nothrow_move_constructible<_Tp>()
549 && noexcept(swap(declval<_Tp&>(), declval<_Tp&>())))
553 if (this->_M_is_engaged() && __other._M_is_engaged())
554 swap(this->_M_get(), __other._M_get());
555 else if (this->_M_is_engaged())
557 __other._M_construct(std::move(this->_M_get()));
560 else if (__other._M_is_engaged())
562 this->_M_construct(std::move(__other._M_get()));
563 __other._M_destruct();
567 // [X.Y.4.5] Observers.
570 { return __constexpr_addressof(this->_M_get()); }
574 { return std::__addressof(this->_M_get()); }
578 { return this->_M_get(); }
582 { return this->_M_get(); }
586 { return std::move(this->_M_get()); }
588 constexpr const _Tp&&
590 { return std::move(this->_M_get()); }
592 constexpr explicit operator bool() const noexcept
593 { return this->_M_is_engaged(); }
598 return this->_M_is_engaged()
600 : (__throw_bad_optional_access("Attempt to access value of a "
601 "disengaged optional object"),
608 return this->_M_is_engaged()
610 : (__throw_bad_optional_access("Attempt to access value of a "
611 "disengaged optional object"),
618 return this->_M_is_engaged()
619 ? std::move(this->_M_get())
620 : (__throw_bad_optional_access("Attempt to access value of a "
621 "disengaged optional object"),
622 std::move(this->_M_get()));
625 constexpr const _Tp&&
628 return this->_M_is_engaged()
629 ? std::move(this->_M_get())
630 : (__throw_bad_optional_access("Attempt to access value of a "
631 "disengaged optional object"),
632 std::move(this->_M_get()));
635 template<typename _Up>
637 value_or(_Up&& __u) const&
639 static_assert(__and_<is_copy_constructible<_Tp>,
640 is_convertible<_Up&&, _Tp>>(),
641 "Cannot return value");
643 return this->_M_is_engaged()
645 : static_cast<_Tp>(std::forward<_Up>(__u));
648 template<typename _Up>
650 value_or(_Up&& __u) &&
652 static_assert(__and_<is_move_constructible<_Tp>,
653 is_convertible<_Up&&, _Tp>>(),
654 "Cannot return value" );
656 return this->_M_is_engaged()
657 ? std::move(this->_M_get())
658 : static_cast<_Tp>(std::forward<_Up>(__u));
662 // [X.Y.8] Comparisons between optional values.
663 template<typename _Tp>
665 operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
667 return static_cast<bool>(__lhs) == static_cast<bool>(__rhs)
668 && (!__lhs || *__lhs == *__rhs);
671 template<typename _Tp>
673 operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
674 { return !(__lhs == __rhs); }
676 template<typename _Tp>
678 operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
680 return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs);
683 template<typename _Tp>
685 operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
686 { return __rhs < __lhs; }
688 template<typename _Tp>
690 operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
691 { return !(__rhs < __lhs); }
693 template<typename _Tp>
695 operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs)
696 { return !(__lhs < __rhs); }
698 // [X.Y.9] Comparisons with nullopt.
699 template<typename _Tp>
701 operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept
704 template<typename _Tp>
706 operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept
709 template<typename _Tp>
711 operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept
712 { return static_cast<bool>(__lhs); }
714 template<typename _Tp>
716 operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept
717 { return static_cast<bool>(__rhs); }
719 template<typename _Tp>
721 operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
724 template<typename _Tp>
726 operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept
727 { return static_cast<bool>(__rhs); }
729 template<typename _Tp>
731 operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept
732 { return static_cast<bool>(__lhs); }
734 template<typename _Tp>
736 operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
739 template<typename _Tp>
741 operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept
744 template<typename _Tp>
746 operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept
749 template<typename _Tp>
751 operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept
754 template<typename _Tp>
756 operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept
759 // [X.Y.10] Comparisons with value type.
760 template<typename _Tp>
762 operator==(const optional<_Tp>& __lhs, const _Tp& __rhs)
763 { return __lhs && *__lhs == __rhs; }
765 template<typename _Tp>
767 operator==(const _Tp& __lhs, const optional<_Tp>& __rhs)
768 { return __rhs && __lhs == *__rhs; }
770 template<typename _Tp>
772 operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs)
773 { return !__lhs || !(*__lhs == __rhs); }
775 template<typename _Tp>
777 operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs)
778 { return !__rhs || !(__lhs == *__rhs); }
780 template<typename _Tp>
782 operator<(const optional<_Tp>& __lhs, const _Tp& __rhs)
783 { return !__lhs || *__lhs < __rhs; }
785 template<typename _Tp>
787 operator<(const _Tp& __lhs, const optional<_Tp>& __rhs)
788 { return __rhs && __lhs < *__rhs; }
790 template<typename _Tp>
792 operator>(const optional<_Tp>& __lhs, const _Tp& __rhs)
793 { return __lhs && __rhs < *__lhs; }
795 template<typename _Tp>
797 operator>(const _Tp& __lhs, const optional<_Tp>& __rhs)
798 { return !__rhs || *__rhs < __lhs; }
800 template<typename _Tp>
802 operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs)
803 { return !__lhs || !(__rhs < *__lhs); }
805 template<typename _Tp>
807 operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs)
808 { return __rhs && !(*__rhs < __lhs); }
810 template<typename _Tp>
812 operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs)
813 { return __lhs && !(*__lhs < __rhs); }
815 template<typename _Tp>
817 operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs)
818 { return !__rhs || !(__lhs < *__rhs); }
821 template<typename _Tp>
823 swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs)
824 noexcept(noexcept(__lhs.swap(__rhs)))
825 { __lhs.swap(__rhs); }
827 template<typename _Tp>
828 constexpr optional<decay_t<_Tp>>
829 make_optional(_Tp&& __t)
830 { return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; }
833 _GLIBCXX_END_NAMESPACE_VERSION
834 } // namespace fundamentals_v1
838 template<typename _Tp>
839 struct hash<experimental::optional<_Tp>>
841 using result_type = size_t;
842 using argument_type = experimental::optional<_Tp>;
845 operator()(const experimental::optional<_Tp>& __t) const
846 noexcept(noexcept(hash<_Tp> {}(*__t)))
848 // We pick an arbitrary hash for disengaged optionals which hopefully
849 // usual values of _Tp won't typically hash to.
850 constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333);
851 return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash;
858 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL