3 // Copyright (C) 2014-2024 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 #define __glibcxx_want_any
35 #include <bits/version.h>
37 #ifdef __cpp_lib_any // C++ >= 17
39 #include <initializer_list>
42 #include <type_traits>
43 #include <bits/utility.h> // in_place_type_t
45 #pragma GCC diagnostic push
46 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // aligned_storage
48 namespace std _GLIBCXX_VISIBILITY(default)
50 _GLIBCXX_BEGIN_NAMESPACE_VERSION
53 * @addtogroup utilities
58 * @brief Exception class thrown by a failed @c any_cast
61 class bad_any_cast : public bad_cast
64 virtual const char* what() const noexcept { return "bad any_cast"; }
67 [[gnu::noreturn]] inline void __throw_bad_any_cast()
77 * @brief A type-safe container of any type.
79 * An `any` object's state is either empty or it stores a contained object
80 * of CopyConstructible type.
86 // Holds either pointer to a heap object or the contained object itself.
89 constexpr _Storage() : _M_ptr{nullptr} {}
91 // Prevent trivial copies of this type, buffer might hold a non-POD.
92 _Storage(const _Storage&) = delete;
93 _Storage& operator=(const _Storage&) = delete;
96 aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
99 template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
100 bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
101 && (alignof(_Tp) <= alignof(_Storage))>
102 using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
104 template<typename _Tp>
105 struct _Manager_internal; // uses small-object optimization
107 template<typename _Tp>
108 struct _Manager_external; // creates contained object on the heap
110 template<typename _Tp>
111 using _Manager = __conditional_t<_Internal<_Tp>::value,
112 _Manager_internal<_Tp>,
113 _Manager_external<_Tp>>;
115 template<typename _Tp, typename _VTp = decay_t<_Tp>>
116 using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
118 /// Emplace with an object created from @p __args as the contained object.
119 template <typename _Tp, typename... _Args,
120 typename _Mgr = _Manager<_Tp>>
121 void __do_emplace(_Args&&... __args)
124 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
125 _M_manager = &_Mgr::_S_manage;
128 /// Emplace with an object created from @p __il and @p __args as
129 /// the contained object.
130 template <typename _Tp, typename _Up, typename... _Args,
131 typename _Mgr = _Manager<_Tp>>
132 void __do_emplace(initializer_list<_Up> __il, _Args&&... __args)
135 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
136 _M_manager = &_Mgr::_S_manage;
139 template <typename _Res, typename _Tp, typename... _Args>
140 using __any_constructible
141 = enable_if<__and_<is_copy_constructible<_Tp>,
142 is_constructible<_Tp, _Args...>>::value,
145 template <typename _Tp, typename... _Args>
146 using __any_constructible_t
147 = typename __any_constructible<bool, _Tp, _Args...>::type;
149 template<typename _VTp, typename... _Args>
151 = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
154 // construct/destruct
156 /// Default constructor, creates an empty object.
157 constexpr any() noexcept : _M_manager(nullptr) { }
159 /// Copy constructor, copies the state of @p __other
160 any(const any& __other)
162 if (!__other.has_value())
163 _M_manager = nullptr;
168 __other._M_manager(_Op_clone, &__other, &__arg);
173 * @brief Move constructor, transfer the state from @p __other
175 * @post @c !__other.has_value() (this postcondition is a GNU extension)
177 any(any&& __other) noexcept
179 if (!__other.has_value())
180 _M_manager = nullptr;
185 __other._M_manager(_Op_xfer, &__other, &__arg);
189 /// Construct with a copy of @p __value as the contained object.
190 template <typename _Tp, typename _VTp = _Decay_if_not_any<_Tp>,
191 typename _Mgr = _Manager<_VTp>,
192 enable_if_t<is_copy_constructible_v<_VTp>
193 && !__is_in_place_type_v<_VTp>, bool> = true>
195 : _M_manager(&_Mgr::_S_manage)
197 _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
200 /// Construct with an object created from @p __args as the contained object.
201 template <typename _Tp, typename... _Args, typename _VTp = decay_t<_Tp>,
202 typename _Mgr = _Manager<_VTp>,
203 __any_constructible_t<_VTp, _Args&&...> = false>
205 any(in_place_type_t<_Tp>, _Args&&... __args)
206 : _M_manager(&_Mgr::_S_manage)
208 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
211 /// Construct with an object created from @p __il and @p __args as
212 /// the contained object.
213 template <typename _Tp, typename _Up, typename... _Args,
214 typename _VTp = decay_t<_Tp>, typename _Mgr = _Manager<_VTp>,
215 __any_constructible_t<_VTp, initializer_list<_Up>&,
218 any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
219 : _M_manager(&_Mgr::_S_manage)
221 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
224 /// Destructor, calls @c reset()
229 /// Copy the state of another object.
231 operator=(const any& __rhs)
238 * @brief Move assignment operator
240 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
243 operator=(any&& __rhs) noexcept
245 if (!__rhs.has_value())
247 else if (this != &__rhs)
252 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
257 /// Store a copy of @p __rhs as the contained object.
258 template<typename _Tp>
259 enable_if_t<is_copy_constructible<_Decay_if_not_any<_Tp>>::value, any&>
260 operator=(_Tp&& __rhs)
262 *this = any(std::forward<_Tp>(__rhs));
266 /// Emplace with an object created from @p __args as the contained object.
267 template <typename _Tp, typename... _Args>
268 __emplace_t<decay_t<_Tp>, _Args...>
269 emplace(_Args&&... __args)
271 using _VTp = decay_t<_Tp>;
272 __do_emplace<_VTp>(std::forward<_Args>(__args)...);
273 return *any::_Manager<_VTp>::_S_access(_M_storage);
276 /// Emplace with an object created from @p __il and @p __args as
277 /// the contained object.
278 template <typename _Tp, typename _Up, typename... _Args>
279 __emplace_t<decay_t<_Tp>, initializer_list<_Up>&, _Args&&...>
280 emplace(initializer_list<_Up> __il, _Args&&... __args)
282 using _VTp = decay_t<_Tp>;
283 __do_emplace<_VTp, _Up>(__il, std::forward<_Args>(__args)...);
284 return *any::_Manager<_VTp>::_S_access(_M_storage);
289 /// If not empty, destroy the contained object.
290 void reset() noexcept
294 _M_manager(_Op_destroy, this, nullptr);
295 _M_manager = nullptr;
299 /// Exchange state with another object.
300 void swap(any& __rhs) noexcept
302 if (!has_value() && !__rhs.has_value())
305 if (has_value() && __rhs.has_value())
312 __arg._M_any = &__tmp;
313 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
314 __arg._M_any = &__rhs;
315 _M_manager(_Op_xfer, this, &__arg);
317 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
321 any* __empty = !has_value() ? this : &__rhs;
322 any* __full = !has_value() ? &__rhs : this;
324 __arg._M_any = __empty;
325 __full->_M_manager(_Op_xfer, __full, &__arg);
331 /// Reports whether there is a contained object or not.
332 bool has_value() const noexcept { return _M_manager != nullptr; }
335 /// The @c typeid of the contained object, or @c typeid(void) if empty.
336 const type_info& type() const noexcept
341 _M_manager(_Op_get_type_info, this, &__arg);
342 return *__arg._M_typeinfo;
346 /// @cond undocumented
347 template<typename _Tp>
348 static constexpr bool __is_valid_cast()
349 { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
354 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
360 const std::type_info* _M_typeinfo;
364 void (*_M_manager)(_Op, const any*, _Arg*);
367 /// @cond undocumented
368 template<typename _Tp>
369 friend void* __any_caster(const any* __any);
372 // Manage in-place contained object.
373 template<typename _Tp>
374 struct _Manager_internal
377 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
379 template<typename _Up>
381 _S_create(_Storage& __storage, _Up&& __value)
383 void* __addr = &__storage._M_buffer;
384 ::new (__addr) _Tp(std::forward<_Up>(__value));
387 template<typename... _Args>
389 _S_create(_Storage& __storage, _Args&&... __args)
391 void* __addr = &__storage._M_buffer;
392 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
396 _S_access(const _Storage& __storage)
398 // The contained object is in __storage._M_buffer
399 const void* __addr = &__storage._M_buffer;
400 return static_cast<_Tp*>(const_cast<void*>(__addr));
404 // Manage external contained object.
405 template<typename _Tp>
406 struct _Manager_external
409 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
411 template<typename _Up>
413 _S_create(_Storage& __storage, _Up&& __value)
415 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
417 template<typename... _Args>
419 _S_create(_Storage& __storage, _Args&&... __args)
421 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
424 _S_access(const _Storage& __storage)
426 // The contained object is in *__storage._M_ptr
427 return static_cast<_Tp*>(__storage._M_ptr);
432 /// Exchange the states of two @c any objects.
433 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
435 /// Create an `any` holding a `_Tp` constructed from `__args...`.
436 template <typename _Tp, typename... _Args>
438 enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>, _Args...>, any>
439 make_any(_Args&&... __args)
441 return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
444 /// Create an `any` holding a `_Tp` constructed from `__il` and `__args...`.
445 template <typename _Tp, typename _Up, typename... _Args>
447 enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>,
448 initializer_list<_Up>&, _Args...>, any>
449 make_any(initializer_list<_Up> __il, _Args&&... __args)
451 return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
455 * @brief Access the contained object.
457 * @tparam _ValueType A const-reference or CopyConstructible type.
458 * @param __any The object to access.
459 * @return The contained object.
460 * @throw bad_any_cast If <code>
461 * __any.type() != typeid(remove_reference_t<_ValueType>)
464 template<typename _ValueType>
465 inline _ValueType any_cast(const any& __any)
467 using _Up = __remove_cvref_t<_ValueType>;
468 static_assert(any::__is_valid_cast<_ValueType>(),
469 "Template argument must be a reference or CopyConstructible type");
470 static_assert(is_constructible_v<_ValueType, const _Up&>,
471 "Template argument must be constructible from a const value.");
472 auto __p = any_cast<_Up>(&__any);
474 return static_cast<_ValueType>(*__p);
475 __throw_bad_any_cast();
479 * @brief Access the contained object.
481 * @tparam _ValueType A reference or CopyConstructible type.
482 * @param __any The object to access.
483 * @return The contained object.
484 * @throw bad_any_cast If <code>
485 * __any.type() != typeid(remove_reference_t<_ValueType>)
490 template<typename _ValueType>
491 inline _ValueType any_cast(any& __any)
493 using _Up = __remove_cvref_t<_ValueType>;
494 static_assert(any::__is_valid_cast<_ValueType>(),
495 "Template argument must be a reference or CopyConstructible type");
496 static_assert(is_constructible_v<_ValueType, _Up&>,
497 "Template argument must be constructible from an lvalue.");
498 auto __p = any_cast<_Up>(&__any);
500 return static_cast<_ValueType>(*__p);
501 __throw_bad_any_cast();
504 template<typename _ValueType>
505 inline _ValueType any_cast(any&& __any)
507 using _Up = __remove_cvref_t<_ValueType>;
508 static_assert(any::__is_valid_cast<_ValueType>(),
509 "Template argument must be a reference or CopyConstructible type");
510 static_assert(is_constructible_v<_ValueType, _Up>,
511 "Template argument must be constructible from an rvalue.");
512 auto __p = any_cast<_Up>(&__any);
514 return static_cast<_ValueType>(std::move(*__p));
515 __throw_bad_any_cast();
519 /// @cond undocumented
520 template<typename _Tp>
521 void* __any_caster(const any* __any)
523 // any_cast<T> returns non-null if __any->type() == typeid(T) and
524 // typeid(T) ignores cv-qualifiers so remove them:
525 using _Up = remove_cv_t<_Tp>;
526 // The contained value has a decayed type, so if decay_t<U> is not U,
527 // then it's not possible to have a contained value of type U:
528 if constexpr (!is_same_v<decay_t<_Up>, _Up>)
530 // Only copy constructible types can be used for contained values:
531 else if constexpr (!is_copy_constructible_v<_Up>)
533 // First try comparing function addresses, which works without RTTI
534 else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
536 || __any->type() == typeid(_Tp)
540 return any::_Manager<_Up>::_S_access(__any->_M_storage);
547 * @brief Access the contained object.
549 * @tparam _ValueType The type of the contained object.
550 * @param __any A pointer to the object to access.
551 * @return The address of the contained object if <code>
552 * __any != nullptr && __any.type() == typeid(_ValueType)
553 * </code>, otherwise a null pointer.
557 template<typename _ValueType>
558 inline const _ValueType* any_cast(const any* __any) noexcept
560 // _GLIBCXX_RESOLVE_LIB_DEFECTS
561 // 3305. any_cast<void>
562 static_assert(!is_void_v<_ValueType>);
564 // As an optimization, don't bother instantiating __any_caster for
565 // function types, since std::any can only hold objects.
566 if constexpr (is_object_v<_ValueType>)
568 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
572 template<typename _ValueType>
573 inline _ValueType* any_cast(any* __any) noexcept
575 static_assert(!is_void_v<_ValueType>);
577 if constexpr (is_object_v<_ValueType>)
579 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
584 template<typename _Tp>
586 any::_Manager_internal<_Tp>::
587 _S_manage(_Op __which, const any* __any, _Arg* __arg)
589 // The contained object is in _M_storage._M_buffer
590 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
594 __arg->_M_obj = const_cast<_Tp*>(__ptr);
596 case _Op_get_type_info:
598 __arg->_M_typeinfo = &typeid(_Tp);
602 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
603 __arg->_M_any->_M_manager = __any->_M_manager;
609 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
610 (std::move(*const_cast<_Tp*>(__ptr)));
612 __arg->_M_any->_M_manager = __any->_M_manager;
613 const_cast<any*>(__any)->_M_manager = nullptr;
618 template<typename _Tp>
620 any::_Manager_external<_Tp>::
621 _S_manage(_Op __which, const any* __any, _Arg* __arg)
623 // The contained object is *_M_storage._M_ptr
624 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
628 __arg->_M_obj = const_cast<_Tp*>(__ptr);
630 case _Op_get_type_info:
632 __arg->_M_typeinfo = &typeid(_Tp);
636 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
637 __arg->_M_any->_M_manager = __any->_M_manager;
643 __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
644 __arg->_M_any->_M_manager = __any->_M_manager;
645 const_cast<any*>(__any)->_M_manager = nullptr;
652 namespace __detail::__variant
654 template<typename> struct _Never_valueless_alt; // see <variant>
656 // Provide the strong exception-safety guarantee when emplacing an
657 // any into a variant.
659 struct _Never_valueless_alt<std::any>
662 } // namespace __detail::__variant
664 _GLIBCXX_END_NAMESPACE_VERSION
667 #pragma GCC diagnostic pop
669 #endif // __cpp_lib_any
670 #endif // _GLIBCXX_ANY