3// Copyright (C) 2014-2025 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.
33#pragma GCC system_header
36#define __glibcxx_want_any
37#include <bits/version.h>
39#ifdef __cpp_lib_any // C++ >= 17
41#include <initializer_list>
45#include <bits/utility.h> // in_place_type_t
47#pragma GCC diagnostic push
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations" // aligned_storage
50namespace std _GLIBCXX_VISIBILITY(default)
52_GLIBCXX_BEGIN_NAMESPACE_VERSION
55 * @addtogroup utilities
60 * @brief Exception class thrown by a failed @c any_cast
63 class bad_any_cast : public bad_cast
66 virtual const char* what() const noexcept { return "bad any_cast"; }
69 [[gnu::noreturn]] inline void __throw_bad_any_cast()
79 * @brief A type-safe container of any type.
81 * An `any` object's state is either empty or it stores a contained object
82 * of CopyConstructible type.
88 // Holds either pointer to a heap object or the contained object itself.
91 constexpr _Storage() : _M_ptr{nullptr} {}
93 // Prevent trivial copies of this type, buffer might hold a non-POD.
94 _Storage(const _Storage&) = delete;
95 _Storage& operator=(const _Storage&) = delete;
98 unsigned char _M_buffer[sizeof(_M_ptr)];
101 template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
102 bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
103 && (alignof(_Tp) <= alignof(_Storage))>
104 using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
106 template<typename _Tp>
107 struct _Manager_internal; // uses small-object optimization
109 template<typename _Tp>
110 struct _Manager_external; // creates contained object on the heap
112 template<typename _Tp>
113 using _Manager = __conditional_t<_Internal<_Tp>::value,
114 _Manager_internal<_Tp>,
115 _Manager_external<_Tp>>;
117 template<typename _Tp, typename _VTp = decay_t<_Tp>>
118 using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
120 /// Emplace with an object created from @p __args as the contained object.
121 template <typename _Tp, typename... _Args,
122 typename _Mgr = _Manager<_Tp>>
123 void __do_emplace(_Args&&... __args)
126 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
127 _M_manager = &_Mgr::_S_manage;
130 /// Emplace with an object created from @p __il and @p __args as
131 /// the contained object.
132 template <typename _Tp, typename _Up, typename... _Args,
133 typename _Mgr = _Manager<_Tp>>
134 void __do_emplace(initializer_list<_Up> __il, _Args&&... __args)
137 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
138 _M_manager = &_Mgr::_S_manage;
141 template <typename _Res, typename _Tp, typename... _Args>
142 using __any_constructible
143 = enable_if<__and_<is_copy_constructible<_Tp>,
144 is_constructible<_Tp, _Args...>>::value,
147 template <typename _Tp, typename... _Args>
148 using __any_constructible_t
149 = typename __any_constructible<bool, _Tp, _Args...>::type;
151 template<typename _VTp, typename... _Args>
153 = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
156 // construct/destruct
158 /// Default constructor, creates an empty object.
159 constexpr any() noexcept : _M_manager(nullptr) { }
161 /// Copy constructor, copies the state of @p __other
162 any(const any& __other)
164 if (!__other.has_value())
165 _M_manager = nullptr;
170 __other._M_manager(_Op_clone, &__other, &__arg);
175 * @brief Move constructor, transfer the state from @p __other
177 * @post @c !__other.has_value() (this postcondition is a GNU extension)
179 any(any&& __other) noexcept
181 if (!__other.has_value())
182 _M_manager = nullptr;
187 __other._M_manager(_Op_xfer, &__other, &__arg);
191 /// Construct with a copy of @p __value as the contained object.
192 template <typename _Tp, typename _VTp = _Decay_if_not_any<_Tp>,
193 typename _Mgr = _Manager<_VTp>,
194 enable_if_t<is_copy_constructible_v<_VTp>
195 && !__is_in_place_type_v<_VTp>, bool> = true>
197 : _M_manager(&_Mgr::_S_manage)
199 _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
202 /// Construct with an object created from @p __args as the contained object.
203 template <typename _Tp, typename... _Args, typename _VTp = decay_t<_Tp>,
204 typename _Mgr = _Manager<_VTp>,
205 __any_constructible_t<_VTp, _Args&&...> = false>
207 any(in_place_type_t<_Tp>, _Args&&... __args)
208 : _M_manager(&_Mgr::_S_manage)
210 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
213 /// Construct with an object created from @p __il and @p __args as
214 /// the contained object.
215 template <typename _Tp, typename _Up, typename... _Args,
216 typename _VTp = decay_t<_Tp>, typename _Mgr = _Manager<_VTp>,
217 __any_constructible_t<_VTp, initializer_list<_Up>&,
220 any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
221 : _M_manager(&_Mgr::_S_manage)
223 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
226 /// Destructor, calls @c reset()
231 /// Copy the state of another object.
233 operator=(const any& __rhs)
240 * @brief Move assignment operator
242 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
245 operator=(any&& __rhs) noexcept
247 if (!__rhs.has_value())
249 else if (this != &__rhs)
254 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
259 /// Store a copy of @p __rhs as the contained object.
260 template<typename _Tp>
261 enable_if_t<is_copy_constructible<_Decay_if_not_any<_Tp>>::value, any&>
262 operator=(_Tp&& __rhs)
264 *this = any(std::forward<_Tp>(__rhs));
268 /// Emplace with an object created from @p __args as the contained object.
269 template <typename _Tp, typename... _Args>
270 __emplace_t<decay_t<_Tp>, _Args...>
271 emplace(_Args&&... __args)
273 using _VTp = decay_t<_Tp>;
274 __do_emplace<_VTp>(std::forward<_Args>(__args)...);
275 return *any::_Manager<_VTp>::_S_access(_M_storage);
278 /// Emplace with an object created from @p __il and @p __args as
279 /// the contained object.
280 template <typename _Tp, typename _Up, typename... _Args>
281 __emplace_t<decay_t<_Tp>, initializer_list<_Up>&, _Args&&...>
282 emplace(initializer_list<_Up> __il, _Args&&... __args)
284 using _VTp = decay_t<_Tp>;
285 __do_emplace<_VTp, _Up>(__il, std::forward<_Args>(__args)...);
286 return *any::_Manager<_VTp>::_S_access(_M_storage);
291 /// If not empty, destroy the contained object.
292 void reset() noexcept
296 _M_manager(_Op_destroy, this, nullptr);
297 _M_manager = nullptr;
301 /// Exchange state with another object.
302 void swap(any& __rhs) noexcept
304 if (!has_value() && !__rhs.has_value())
307 if (has_value() && __rhs.has_value())
314 __arg._M_any = &__tmp;
315 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
316 __arg._M_any = &__rhs;
317 _M_manager(_Op_xfer, this, &__arg);
319 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
323 any* __empty = !has_value() ? this : &__rhs;
324 any* __full = !has_value() ? &__rhs : this;
326 __arg._M_any = __empty;
327 __full->_M_manager(_Op_xfer, __full, &__arg);
333 /// Reports whether there is a contained object or not.
334 bool has_value() const noexcept { return _M_manager != nullptr; }
337 /// The @c typeid of the contained object, or @c typeid(void) if empty.
338 const type_info& type() const noexcept
343 _M_manager(_Op_get_type_info, this, &__arg);
344 return *__arg._M_typeinfo;
348 /// @cond undocumented
349 template<typename _Tp>
350 static constexpr bool __is_valid_cast()
351 { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
356 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
362 const std::type_info* _M_typeinfo;
366 void (*_M_manager)(_Op, const any*, _Arg*);
369 /// @cond undocumented
370 template<typename _Tp>
371 friend void* __any_caster(const any* __any);
374 // Manage in-place contained object.
375 template<typename _Tp>
376 struct _Manager_internal
379 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
381 template<typename _Up>
383 _S_create(_Storage& __storage, _Up&& __value)
385 void* __addr = &__storage._M_buffer;
386 ::new (__addr) _Tp(std::forward<_Up>(__value));
389 template<typename... _Args>
391 _S_create(_Storage& __storage, _Args&&... __args)
393 void* __addr = &__storage._M_buffer;
394 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
398 _S_access(const _Storage& __storage)
400 // The contained object is in __storage._M_buffer
401 const void* __addr = &__storage._M_buffer;
402 return static_cast<_Tp*>(const_cast<void*>(__addr));
406 // Manage external contained object.
407 template<typename _Tp>
408 struct _Manager_external
411 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
413 template<typename _Up>
415 _S_create(_Storage& __storage, _Up&& __value)
417 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
419 template<typename... _Args>
421 _S_create(_Storage& __storage, _Args&&... __args)
423 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
426 _S_access(const _Storage& __storage)
428 // The contained object is in *__storage._M_ptr
429 return static_cast<_Tp*>(__storage._M_ptr);
434 /// Exchange the states of two @c any objects.
435 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
437 /// Create an `any` holding a `_Tp` constructed from `__args...`.
438 template <typename _Tp, typename... _Args>
440 enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>, _Args...>, any>
441 make_any(_Args&&... __args)
443 return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
446 /// Create an `any` holding a `_Tp` constructed from `__il` and `__args...`.
447 template <typename _Tp, typename _Up, typename... _Args>
449 enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>,
450 initializer_list<_Up>&, _Args...>, any>
451 make_any(initializer_list<_Up> __il, _Args&&... __args)
453 return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
457 * @brief Access the contained object.
459 * @tparam _ValueType A const-reference or CopyConstructible type.
460 * @param __any The object to access.
461 * @return The contained object.
462 * @throw bad_any_cast If <code>
463 * __any.type() != typeid(remove_reference_t<_ValueType>)
466 template<typename _ValueType>
467 inline _ValueType any_cast(const any& __any)
469 using _Up = __remove_cvref_t<_ValueType>;
470 static_assert(any::__is_valid_cast<_ValueType>(),
471 "Template argument must be a reference or CopyConstructible type");
472 static_assert(is_constructible_v<_ValueType, const _Up&>,
473 "Template argument must be constructible from a const value.");
474 auto __p = any_cast<_Up>(&__any);
476 return static_cast<_ValueType>(*__p);
477 __throw_bad_any_cast();
481 * @brief Access the contained object.
483 * @tparam _ValueType A reference or CopyConstructible type.
484 * @param __any The object to access.
485 * @return The contained object.
486 * @throw bad_any_cast If <code>
487 * __any.type() != typeid(remove_reference_t<_ValueType>)
492 template<typename _ValueType>
493 inline _ValueType any_cast(any& __any)
495 using _Up = __remove_cvref_t<_ValueType>;
496 static_assert(any::__is_valid_cast<_ValueType>(),
497 "Template argument must be a reference or CopyConstructible type");
498 static_assert(is_constructible_v<_ValueType, _Up&>,
499 "Template argument must be constructible from an lvalue.");
500 auto __p = any_cast<_Up>(&__any);
502 return static_cast<_ValueType>(*__p);
503 __throw_bad_any_cast();
506 template<typename _ValueType>
507 inline _ValueType any_cast(any&& __any)
509 using _Up = __remove_cvref_t<_ValueType>;
510 static_assert(any::__is_valid_cast<_ValueType>(),
511 "Template argument must be a reference or CopyConstructible type");
512 static_assert(is_constructible_v<_ValueType, _Up>,
513 "Template argument must be constructible from an rvalue.");
514 auto __p = any_cast<_Up>(&__any);
516 return static_cast<_ValueType>(std::move(*__p));
517 __throw_bad_any_cast();
521 /// @cond undocumented
522 template<typename _Tp>
523 void* __any_caster(const any* __any)
525 // any_cast<T> returns non-null if __any->type() == typeid(T) and
526 // typeid(T) ignores cv-qualifiers so remove them:
527 using _Up = remove_cv_t<_Tp>;
528 // The contained value has a decayed type, so if decay_t<U> is not U,
529 // then it's not possible to have a contained value of type U:
530 if constexpr (!is_same_v<decay_t<_Up>, _Up>)
532 // Only copy constructible types can be used for contained values:
533 else if constexpr (!is_copy_constructible_v<_Up>)
535 // First try comparing function addresses, which works without RTTI
536 else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
538 || __any->type() == typeid(_Tp)
542 return any::_Manager<_Up>::_S_access(__any->_M_storage);
549 * @brief Access the contained object.
551 * @tparam _ValueType The type of the contained object.
552 * @param __any A pointer to the object to access.
553 * @return The address of the contained object if <code>
554 * __any != nullptr && __any.type() == typeid(_ValueType)
555 * </code>, otherwise a null pointer.
559 template<typename _ValueType>
560 inline const _ValueType* any_cast(const any* __any) noexcept
562 // _GLIBCXX_RESOLVE_LIB_DEFECTS
563 // 3305. any_cast<void>
564 static_assert(!is_void_v<_ValueType>);
566 // As an optimization, don't bother instantiating __any_caster for
567 // function types, since std::any can only hold objects.
568 if constexpr (is_object_v<_ValueType>)
570 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
574 template<typename _ValueType>
575 inline _ValueType* any_cast(any* __any) noexcept
577 static_assert(!is_void_v<_ValueType>);
579 if constexpr (is_object_v<_ValueType>)
581 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
586 template<typename _Tp>
588 any::_Manager_internal<_Tp>::
589 _S_manage(_Op __which, const any* __any, _Arg* __arg)
591 // The contained object is in _M_storage._M_buffer
592 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
596 __arg->_M_obj = const_cast<_Tp*>(__ptr);
598 case _Op_get_type_info:
600 __arg->_M_typeinfo = &typeid(_Tp);
604 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
605 __arg->_M_any->_M_manager = __any->_M_manager;
611 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
612 (std::move(*const_cast<_Tp*>(__ptr)));
614 __arg->_M_any->_M_manager = __any->_M_manager;
615 const_cast<any*>(__any)->_M_manager = nullptr;
620 template<typename _Tp>
622 any::_Manager_external<_Tp>::
623 _S_manage(_Op __which, const any* __any, _Arg* __arg)
625 // The contained object is *_M_storage._M_ptr
626 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
630 __arg->_M_obj = const_cast<_Tp*>(__ptr);
632 case _Op_get_type_info:
634 __arg->_M_typeinfo = &typeid(_Tp);
638 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
639 __arg->_M_any->_M_manager = __any->_M_manager;
645 __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
646 __arg->_M_any->_M_manager = __any->_M_manager;
647 const_cast<any*>(__any)->_M_manager = nullptr;
654 namespace __detail::__variant
656 template<typename> struct _Never_valueless_alt; // see <variant>
658 // Provide the strong exception-safety guarantee when emplacing an
659 // any into a variant.
661 struct _Never_valueless_alt<std::any>
664 } // namespace __detail::__variant
666_GLIBCXX_END_NAMESPACE_VERSION
669#pragma GCC diagnostic pop
671#endif // __cpp_lib_any
672#endif // _GLIBCXX_ANY