3 // Copyright (C) 2014-2021 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/>.
26 * This is a Standard C++ Library header.
30 #define _GLIBCXX_ANY 1
32 #pragma GCC system_header
34 #if __cplusplus >= 201703L
36 #include <initializer_list>
39 #include <type_traits>
40 #include <bits/utility.h> // in_place_type_t
42 namespace std _GLIBCXX_VISIBILITY(default)
44 _GLIBCXX_BEGIN_NAMESPACE_VERSION
47 * @addtogroup utilities
52 * @brief Exception class thrown by a failed @c any_cast
55 class bad_any_cast : public bad_cast
58 virtual const char* what() const noexcept { return "bad any_cast"; }
61 [[gnu::noreturn]] inline void __throw_bad_any_cast()
70 #define __cpp_lib_any 201606L
73 * @brief A type-safe container of any type.
75 * An `any` object's state is either empty or it stores a contained object
76 * of CopyConstructible type.
82 // Holds either pointer to a heap object or the contained object itself.
85 constexpr _Storage() : _M_ptr{nullptr} {}
87 // Prevent trivial copies of this type, buffer might hold a non-POD.
88 _Storage(const _Storage&) = delete;
89 _Storage& operator=(const _Storage&) = delete;
92 aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
95 template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
96 bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
97 && (alignof(_Tp) <= alignof(_Storage))>
98 using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
100 template<typename _Tp>
101 struct _Manager_internal; // uses small-object optimization
103 template<typename _Tp>
104 struct _Manager_external; // creates contained object on the heap
106 template<typename _Tp>
107 using _Manager = __conditional_t<_Internal<_Tp>::value,
108 _Manager_internal<_Tp>,
109 _Manager_external<_Tp>>;
111 template<typename _Tp, typename _VTp = decay_t<_Tp>>
112 using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
114 /// Emplace with an object created from @p __args as the contained object.
115 template <typename _Tp, typename... _Args,
116 typename _Mgr = _Manager<_Tp>>
117 void __do_emplace(_Args&&... __args)
120 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
121 _M_manager = &_Mgr::_S_manage;
124 /// Emplace with an object created from @p __il and @p __args as
125 /// the contained object.
126 template <typename _Tp, typename _Up, typename... _Args,
127 typename _Mgr = _Manager<_Tp>>
128 void __do_emplace(initializer_list<_Up> __il, _Args&&... __args)
131 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
132 _M_manager = &_Mgr::_S_manage;
135 template <typename _Res, typename _Tp, typename... _Args>
136 using __any_constructible
137 = enable_if<__and_<is_copy_constructible<_Tp>,
138 is_constructible<_Tp, _Args...>>::value,
141 template <typename _Tp, typename... _Args>
142 using __any_constructible_t
143 = typename __any_constructible<bool, _Tp, _Args...>::type;
145 template<typename _VTp, typename... _Args>
147 = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
150 // construct/destruct
152 /// Default constructor, creates an empty object.
153 constexpr any() noexcept : _M_manager(nullptr) { }
155 /// Copy constructor, copies the state of @p __other
156 any(const any& __other)
158 if (!__other.has_value())
159 _M_manager = nullptr;
164 __other._M_manager(_Op_clone, &__other, &__arg);
169 * @brief Move constructor, transfer the state from @p __other
171 * @post @c !__other.has_value() (this postcondition is a GNU extension)
173 any(any&& __other) noexcept
175 if (!__other.has_value())
176 _M_manager = nullptr;
181 __other._M_manager(_Op_xfer, &__other, &__arg);
185 /// Construct with a copy of @p __value as the contained object.
186 template <typename _Tp, typename _VTp = _Decay_if_not_any<_Tp>,
187 typename _Mgr = _Manager<_VTp>,
188 typename = _Require<__not_<__is_in_place_type<_VTp>>,
189 is_copy_constructible<_VTp>>>
191 : _M_manager(&_Mgr::_S_manage)
193 _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
196 /// Construct with an object created from @p __args as the contained object.
197 template <typename _Tp, typename... _Args, typename _VTp = decay_t<_Tp>,
198 typename _Mgr = _Manager<_VTp>,
199 __any_constructible_t<_VTp, _Args&&...> = false>
201 any(in_place_type_t<_Tp>, _Args&&... __args)
202 : _M_manager(&_Mgr::_S_manage)
204 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
207 /// Construct with an object created from @p __il and @p __args as
208 /// the contained object.
209 template <typename _Tp, typename _Up, typename... _Args,
210 typename _VTp = decay_t<_Tp>, typename _Mgr = _Manager<_VTp>,
211 __any_constructible_t<_VTp, initializer_list<_Up>&,
214 any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
215 : _M_manager(&_Mgr::_S_manage)
217 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
220 /// Destructor, calls @c reset()
225 /// Copy the state of another object.
227 operator=(const any& __rhs)
234 * @brief Move assignment operator
236 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
239 operator=(any&& __rhs) noexcept
241 if (!__rhs.has_value())
243 else if (this != &__rhs)
248 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
253 /// Store a copy of @p __rhs as the contained object.
254 template<typename _Tp>
255 enable_if_t<is_copy_constructible<_Decay_if_not_any<_Tp>>::value, any&>
256 operator=(_Tp&& __rhs)
258 *this = any(std::forward<_Tp>(__rhs));
262 /// Emplace with an object created from @p __args as the contained object.
263 template <typename _Tp, typename... _Args>
264 __emplace_t<decay_t<_Tp>, _Args...>
265 emplace(_Args&&... __args)
267 using _VTp = decay_t<_Tp>;
268 __do_emplace<_VTp>(std::forward<_Args>(__args)...);
269 return *any::_Manager<_VTp>::_S_access(_M_storage);
272 /// Emplace with an object created from @p __il and @p __args as
273 /// the contained object.
274 template <typename _Tp, typename _Up, typename... _Args>
275 __emplace_t<decay_t<_Tp>, initializer_list<_Up>&, _Args&&...>
276 emplace(initializer_list<_Up> __il, _Args&&... __args)
278 using _VTp = decay_t<_Tp>;
279 __do_emplace<_VTp, _Up>(__il, std::forward<_Args>(__args)...);
280 return *any::_Manager<_VTp>::_S_access(_M_storage);
285 /// If not empty, destroy the contained object.
286 void reset() noexcept
290 _M_manager(_Op_destroy, this, nullptr);
291 _M_manager = nullptr;
295 /// Exchange state with another object.
296 void swap(any& __rhs) noexcept
298 if (!has_value() && !__rhs.has_value())
301 if (has_value() && __rhs.has_value())
308 __arg._M_any = &__tmp;
309 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
310 __arg._M_any = &__rhs;
311 _M_manager(_Op_xfer, this, &__arg);
313 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
317 any* __empty = !has_value() ? this : &__rhs;
318 any* __full = !has_value() ? &__rhs : this;
320 __arg._M_any = __empty;
321 __full->_M_manager(_Op_xfer, __full, &__arg);
327 /// Reports whether there is a contained object or not.
328 bool has_value() const noexcept { return _M_manager != nullptr; }
331 /// The @c typeid of the contained object, or @c typeid(void) if empty.
332 const type_info& type() const noexcept
337 _M_manager(_Op_get_type_info, this, &__arg);
338 return *__arg._M_typeinfo;
342 /// @cond undocumented
343 template<typename _Tp>
344 static constexpr bool __is_valid_cast()
345 { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
350 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
356 const std::type_info* _M_typeinfo;
360 void (*_M_manager)(_Op, const any*, _Arg*);
363 /// @cond undocumented
364 template<typename _Tp>
365 friend void* __any_caster(const any* __any);
368 // Manage in-place contained object.
369 template<typename _Tp>
370 struct _Manager_internal
373 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
375 template<typename _Up>
377 _S_create(_Storage& __storage, _Up&& __value)
379 void* __addr = &__storage._M_buffer;
380 ::new (__addr) _Tp(std::forward<_Up>(__value));
383 template<typename... _Args>
385 _S_create(_Storage& __storage, _Args&&... __args)
387 void* __addr = &__storage._M_buffer;
388 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
392 _S_access(const _Storage& __storage)
394 // The contained object is in __storage._M_buffer
395 const void* __addr = &__storage._M_buffer;
396 return static_cast<_Tp*>(const_cast<void*>(__addr));
400 // Manage external contained object.
401 template<typename _Tp>
402 struct _Manager_external
405 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
407 template<typename _Up>
409 _S_create(_Storage& __storage, _Up&& __value)
411 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
413 template<typename... _Args>
415 _S_create(_Storage& __storage, _Args&&... __args)
417 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
420 _S_access(const _Storage& __storage)
422 // The contained object is in *__storage._M_ptr
423 return static_cast<_Tp*>(__storage._M_ptr);
428 /// Exchange the states of two @c any objects.
429 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
431 /// Create an any holding a @c _Tp constructed from @c __args.
432 template <typename _Tp, typename... _Args>
433 any make_any(_Args&&... __args)
435 return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
438 /// Create an any holding a @c _Tp constructed from @c __il and @c __args.
439 template <typename _Tp, typename _Up, typename... _Args>
440 any make_any(initializer_list<_Up> __il, _Args&&... __args)
442 return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
446 * @brief Access the contained object.
448 * @tparam _ValueType A const-reference or CopyConstructible type.
449 * @param __any The object to access.
450 * @return The contained object.
451 * @throw bad_any_cast If <code>
452 * __any.type() != typeid(remove_reference_t<_ValueType>)
455 template<typename _ValueType>
456 inline _ValueType any_cast(const any& __any)
458 using _Up = __remove_cvref_t<_ValueType>;
459 static_assert(any::__is_valid_cast<_ValueType>(),
460 "Template argument must be a reference or CopyConstructible type");
461 static_assert(is_constructible_v<_ValueType, const _Up&>,
462 "Template argument must be constructible from a const value.");
463 auto __p = any_cast<_Up>(&__any);
465 return static_cast<_ValueType>(*__p);
466 __throw_bad_any_cast();
470 * @brief Access the contained object.
472 * @tparam _ValueType A reference or CopyConstructible type.
473 * @param __any The object to access.
474 * @return The contained object.
475 * @throw bad_any_cast If <code>
476 * __any.type() != typeid(remove_reference_t<_ValueType>)
481 template<typename _ValueType>
482 inline _ValueType any_cast(any& __any)
484 using _Up = __remove_cvref_t<_ValueType>;
485 static_assert(any::__is_valid_cast<_ValueType>(),
486 "Template argument must be a reference or CopyConstructible type");
487 static_assert(is_constructible_v<_ValueType, _Up&>,
488 "Template argument must be constructible from an lvalue.");
489 auto __p = any_cast<_Up>(&__any);
491 return static_cast<_ValueType>(*__p);
492 __throw_bad_any_cast();
495 template<typename _ValueType>
496 inline _ValueType any_cast(any&& __any)
498 using _Up = __remove_cvref_t<_ValueType>;
499 static_assert(any::__is_valid_cast<_ValueType>(),
500 "Template argument must be a reference or CopyConstructible type");
501 static_assert(is_constructible_v<_ValueType, _Up>,
502 "Template argument must be constructible from an rvalue.");
503 auto __p = any_cast<_Up>(&__any);
505 return static_cast<_ValueType>(std::move(*__p));
506 __throw_bad_any_cast();
510 /// @cond undocumented
511 template<typename _Tp>
512 void* __any_caster(const any* __any)
514 // any_cast<T> returns non-null if __any->type() == typeid(T) and
515 // typeid(T) ignores cv-qualifiers so remove them:
516 using _Up = remove_cv_t<_Tp>;
517 // The contained value has a decayed type, so if decay_t<U> is not U,
518 // then it's not possible to have a contained value of type U:
519 if constexpr (!is_same_v<decay_t<_Up>, _Up>)
521 // Only copy constructible types can be used for contained values:
522 else if constexpr (!is_copy_constructible_v<_Up>)
524 // First try comparing function addresses, which works without RTTI
525 else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
527 || __any->type() == typeid(_Tp)
531 return any::_Manager<_Up>::_S_access(__any->_M_storage);
538 * @brief Access the contained object.
540 * @tparam _ValueType The type of the contained object.
541 * @param __any A pointer to the object to access.
542 * @return The address of the contained object if <code>
543 * __any != nullptr && __any.type() == typeid(_ValueType)
544 * </code>, otherwise a null pointer.
548 template<typename _ValueType>
549 inline const _ValueType* any_cast(const any* __any) noexcept
551 if constexpr (is_object_v<_ValueType>)
553 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
557 template<typename _ValueType>
558 inline _ValueType* any_cast(any* __any) noexcept
560 if constexpr (is_object_v<_ValueType>)
562 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
567 template<typename _Tp>
569 any::_Manager_internal<_Tp>::
570 _S_manage(_Op __which, const any* __any, _Arg* __arg)
572 // The contained object is in _M_storage._M_buffer
573 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
577 __arg->_M_obj = const_cast<_Tp*>(__ptr);
579 case _Op_get_type_info:
581 __arg->_M_typeinfo = &typeid(_Tp);
585 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
586 __arg->_M_any->_M_manager = __any->_M_manager;
592 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
593 (std::move(*const_cast<_Tp*>(__ptr)));
595 __arg->_M_any->_M_manager = __any->_M_manager;
596 const_cast<any*>(__any)->_M_manager = nullptr;
601 template<typename _Tp>
603 any::_Manager_external<_Tp>::
604 _S_manage(_Op __which, const any* __any, _Arg* __arg)
606 // The contained object is *_M_storage._M_ptr
607 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
611 __arg->_M_obj = const_cast<_Tp*>(__ptr);
613 case _Op_get_type_info:
615 __arg->_M_typeinfo = &typeid(_Tp);
619 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
620 __arg->_M_any->_M_manager = __any->_M_manager;
626 __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
627 __arg->_M_any->_M_manager = __any->_M_manager;
628 const_cast<any*>(__any)->_M_manager = nullptr;
635 namespace __detail::__variant
637 template<typename> struct _Never_valueless_alt; // see <variant>
639 // Provide the strong exception-safety guarantee when emplacing an
640 // any into a variant.
642 struct _Never_valueless_alt<std::any>
645 } // namespace __detail::__variant
647 _GLIBCXX_END_NAMESPACE_VERSION
651 #endif // _GLIBCXX_ANY