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 @c any object's state is either empty or it stores a contained object
76 * of CopyConstructible type.
80 // Holds either pointer to a heap object or the contained object itself.
83 constexpr _Storage() : _M_ptr{nullptr} {}
85 // Prevent trivial copies of this type, buffer might hold a non-POD.
86 _Storage(const _Storage&) = delete;
87 _Storage& operator=(const _Storage&) = delete;
90 aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
93 template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
94 bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
95 && (alignof(_Tp) <= alignof(_Storage))>
96 using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
98 template<typename _Tp>
99 struct _Manager_internal; // uses small-object optimization
101 template<typename _Tp>
102 struct _Manager_external; // creates contained object on the heap
104 template<typename _Tp>
105 using _Manager = __conditional_t<_Internal<_Tp>::value,
106 _Manager_internal<_Tp>,
107 _Manager_external<_Tp>>;
109 template<typename _Tp, typename _VTp = decay_t<_Tp>>
110 using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
112 /// Emplace with an object created from @p __args as the contained object.
113 template <typename _Tp, typename... _Args,
114 typename _Mgr = _Manager<_Tp>>
115 void __do_emplace(_Args&&... __args)
118 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
119 _M_manager = &_Mgr::_S_manage;
122 /// Emplace with an object created from @p __il and @p __args as
123 /// the contained object.
124 template <typename _Tp, typename _Up, typename... _Args,
125 typename _Mgr = _Manager<_Tp>>
126 void __do_emplace(initializer_list<_Up> __il, _Args&&... __args)
129 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
130 _M_manager = &_Mgr::_S_manage;
133 template <typename _Res, typename _Tp, typename... _Args>
134 using __any_constructible
135 = enable_if<__and_<is_copy_constructible<_Tp>,
136 is_constructible<_Tp, _Args...>>::value,
139 template <typename _Tp, typename... _Args>
140 using __any_constructible_t
141 = typename __any_constructible<bool, _Tp, _Args...>::type;
143 template<typename _VTp, typename... _Args>
145 = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
148 // construct/destruct
150 /// Default constructor, creates an empty object.
151 constexpr any() noexcept : _M_manager(nullptr) { }
153 /// Copy constructor, copies the state of @p __other
154 any(const any& __other)
156 if (!__other.has_value())
157 _M_manager = nullptr;
162 __other._M_manager(_Op_clone, &__other, &__arg);
167 * @brief Move constructor, transfer the state from @p __other
169 * @post @c !__other.has_value() (this postcondition is a GNU extension)
171 any(any&& __other) noexcept
173 if (!__other.has_value())
174 _M_manager = nullptr;
179 __other._M_manager(_Op_xfer, &__other, &__arg);
183 /// Construct with a copy of @p __value as the contained object.
184 template <typename _Tp, typename _VTp = _Decay_if_not_any<_Tp>,
185 typename _Mgr = _Manager<_VTp>,
186 enable_if_t<is_copy_constructible<_VTp>::value
187 && !__is_in_place_type<_VTp>::value, bool> = true>
189 : _M_manager(&_Mgr::_S_manage)
191 _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
194 /// Construct with an object created from @p __args as the contained object.
195 template <typename _Tp, typename... _Args, typename _VTp = decay_t<_Tp>,
196 typename _Mgr = _Manager<_VTp>,
197 __any_constructible_t<_VTp, _Args&&...> = false>
199 any(in_place_type_t<_Tp>, _Args&&... __args)
200 : _M_manager(&_Mgr::_S_manage)
202 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
205 /// Construct with an object created from @p __il and @p __args as
206 /// the contained object.
207 template <typename _Tp, typename _Up, typename... _Args,
208 typename _VTp = decay_t<_Tp>, typename _Mgr = _Manager<_VTp>,
209 __any_constructible_t<_VTp, initializer_list<_Up>&,
212 any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
213 : _M_manager(&_Mgr::_S_manage)
215 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
218 /// Destructor, calls @c reset()
223 /// Copy the state of another object.
225 operator=(const any& __rhs)
232 * @brief Move assignment operator
234 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
237 operator=(any&& __rhs) noexcept
239 if (!__rhs.has_value())
241 else if (this != &__rhs)
246 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
251 /// Store a copy of @p __rhs as the contained object.
252 template<typename _Tp>
253 enable_if_t<is_copy_constructible<_Decay_if_not_any<_Tp>>::value, any&>
254 operator=(_Tp&& __rhs)
256 *this = any(std::forward<_Tp>(__rhs));
260 /// Emplace with an object created from @p __args as the contained object.
261 template <typename _Tp, typename... _Args>
262 __emplace_t<decay_t<_Tp>, _Args...>
263 emplace(_Args&&... __args)
265 using _VTp = decay_t<_Tp>;
266 __do_emplace<_VTp>(std::forward<_Args>(__args)...);
267 return *any::_Manager<_VTp>::_S_access(_M_storage);
270 /// Emplace with an object created from @p __il and @p __args as
271 /// the contained object.
272 template <typename _Tp, typename _Up, typename... _Args>
273 __emplace_t<decay_t<_Tp>, initializer_list<_Up>&, _Args&&...>
274 emplace(initializer_list<_Up> __il, _Args&&... __args)
276 using _VTp = decay_t<_Tp>;
277 __do_emplace<_VTp, _Up>(__il, std::forward<_Args>(__args)...);
278 return *any::_Manager<_VTp>::_S_access(_M_storage);
283 /// If not empty, destroy the contained object.
284 void reset() noexcept
288 _M_manager(_Op_destroy, this, nullptr);
289 _M_manager = nullptr;
293 /// Exchange state with another object.
294 void swap(any& __rhs) noexcept
296 if (!has_value() && !__rhs.has_value())
299 if (has_value() && __rhs.has_value())
306 __arg._M_any = &__tmp;
307 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
308 __arg._M_any = &__rhs;
309 _M_manager(_Op_xfer, this, &__arg);
311 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
315 any* __empty = !has_value() ? this : &__rhs;
316 any* __full = !has_value() ? &__rhs : this;
318 __arg._M_any = __empty;
319 __full->_M_manager(_Op_xfer, __full, &__arg);
325 /// Reports whether there is a contained object or not.
326 bool has_value() const noexcept { return _M_manager != nullptr; }
329 /// The @c typeid of the contained object, or @c typeid(void) if empty.
330 const type_info& type() const noexcept
335 _M_manager(_Op_get_type_info, this, &__arg);
336 return *__arg._M_typeinfo;
340 template<typename _Tp>
341 static constexpr bool __is_valid_cast()
342 { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
346 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
352 const std::type_info* _M_typeinfo;
356 void (*_M_manager)(_Op, const any*, _Arg*);
359 template<typename _Tp>
360 friend void* __any_caster(const any* __any);
362 // Manage in-place contained object.
363 template<typename _Tp>
364 struct _Manager_internal
367 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
369 template<typename _Up>
371 _S_create(_Storage& __storage, _Up&& __value)
373 void* __addr = &__storage._M_buffer;
374 ::new (__addr) _Tp(std::forward<_Up>(__value));
377 template<typename... _Args>
379 _S_create(_Storage& __storage, _Args&&... __args)
381 void* __addr = &__storage._M_buffer;
382 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
386 _S_access(const _Storage& __storage)
388 // The contained object is in __storage._M_buffer
389 const void* __addr = &__storage._M_buffer;
390 return static_cast<_Tp*>(const_cast<void*>(__addr));
394 // Manage external contained object.
395 template<typename _Tp>
396 struct _Manager_external
399 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
401 template<typename _Up>
403 _S_create(_Storage& __storage, _Up&& __value)
405 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
407 template<typename... _Args>
409 _S_create(_Storage& __storage, _Args&&... __args)
411 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
414 _S_access(const _Storage& __storage)
416 // The contained object is in *__storage._M_ptr
417 return static_cast<_Tp*>(__storage._M_ptr);
422 /// Exchange the states of two @c any objects.
423 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
425 /// Create an any holding a @c _Tp constructed from @c __args.
426 template <typename _Tp, typename... _Args>
427 any make_any(_Args&&... __args)
429 return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
432 /// Create an any holding a @c _Tp constructed from @c __il and @c __args.
433 template <typename _Tp, typename _Up, typename... _Args>
434 any make_any(initializer_list<_Up> __il, _Args&&... __args)
436 return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
440 * @brief Access the contained object.
442 * @tparam _ValueType A const-reference or CopyConstructible type.
443 * @param __any The object to access.
444 * @return The contained object.
445 * @throw bad_any_cast If <code>
446 * __any.type() != typeid(remove_reference_t<_ValueType>)
449 template<typename _ValueType>
450 inline _ValueType any_cast(const any& __any)
452 using _Up = __remove_cvref_t<_ValueType>;
453 static_assert(any::__is_valid_cast<_ValueType>(),
454 "Template argument must be a reference or CopyConstructible type");
455 static_assert(is_constructible_v<_ValueType, const _Up&>,
456 "Template argument must be constructible from a const value.");
457 auto __p = any_cast<_Up>(&__any);
459 return static_cast<_ValueType>(*__p);
460 __throw_bad_any_cast();
464 * @brief Access the contained object.
466 * @tparam _ValueType A reference or CopyConstructible type.
467 * @param __any The object to access.
468 * @return The contained object.
469 * @throw bad_any_cast If <code>
470 * __any.type() != typeid(remove_reference_t<_ValueType>)
475 template<typename _ValueType>
476 inline _ValueType any_cast(any& __any)
478 using _Up = __remove_cvref_t<_ValueType>;
479 static_assert(any::__is_valid_cast<_ValueType>(),
480 "Template argument must be a reference or CopyConstructible type");
481 static_assert(is_constructible_v<_ValueType, _Up&>,
482 "Template argument must be constructible from an lvalue.");
483 auto __p = any_cast<_Up>(&__any);
485 return static_cast<_ValueType>(*__p);
486 __throw_bad_any_cast();
489 template<typename _ValueType>
490 inline _ValueType any_cast(any&& __any)
492 using _Up = __remove_cvref_t<_ValueType>;
493 static_assert(any::__is_valid_cast<_ValueType>(),
494 "Template argument must be a reference or CopyConstructible type");
495 static_assert(is_constructible_v<_ValueType, _Up>,
496 "Template argument must be constructible from an rvalue.");
497 auto __p = any_cast<_Up>(&__any);
499 return static_cast<_ValueType>(std::move(*__p));
500 __throw_bad_any_cast();
504 /// @cond undocumented
505 template<typename _Tp>
506 void* __any_caster(const any* __any)
508 // any_cast<T> returns non-null if __any->type() == typeid(T) and
509 // typeid(T) ignores cv-qualifiers so remove them:
510 using _Up = remove_cv_t<_Tp>;
511 // The contained value has a decayed type, so if decay_t<U> is not U,
512 // then it's not possible to have a contained value of type U:
513 if constexpr (!is_same_v<decay_t<_Up>, _Up>)
515 // Only copy constructible types can be used for contained values:
516 else if constexpr (!is_copy_constructible_v<_Up>)
518 // First try comparing function addresses, which works without RTTI
519 else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
521 || __any->type() == typeid(_Tp)
525 return any::_Manager<_Up>::_S_access(__any->_M_storage);
532 * @brief Access the contained object.
534 * @tparam _ValueType The type of the contained object.
535 * @param __any A pointer to the object to access.
536 * @return The address of the contained object if <code>
537 * __any != nullptr && __any.type() == typeid(_ValueType)
538 * </code>, otherwise a null pointer.
542 template<typename _ValueType>
543 inline const _ValueType* any_cast(const any* __any) noexcept
545 if constexpr (is_object_v<_ValueType>)
547 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
551 template<typename _ValueType>
552 inline _ValueType* any_cast(any* __any) noexcept
554 if constexpr (is_object_v<_ValueType>)
556 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
561 template<typename _Tp>
563 any::_Manager_internal<_Tp>::
564 _S_manage(_Op __which, const any* __any, _Arg* __arg)
566 // The contained object is in _M_storage._M_buffer
567 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
571 __arg->_M_obj = const_cast<_Tp*>(__ptr);
573 case _Op_get_type_info:
575 __arg->_M_typeinfo = &typeid(_Tp);
579 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
580 __arg->_M_any->_M_manager = __any->_M_manager;
586 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
587 (std::move(*const_cast<_Tp*>(__ptr)));
589 __arg->_M_any->_M_manager = __any->_M_manager;
590 const_cast<any*>(__any)->_M_manager = nullptr;
595 template<typename _Tp>
597 any::_Manager_external<_Tp>::
598 _S_manage(_Op __which, const any* __any, _Arg* __arg)
600 // The contained object is *_M_storage._M_ptr
601 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
605 __arg->_M_obj = const_cast<_Tp*>(__ptr);
607 case _Op_get_type_info:
609 __arg->_M_typeinfo = &typeid(_Tp);
613 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
614 __arg->_M_any->_M_manager = __any->_M_manager;
620 __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
621 __arg->_M_any->_M_manager = __any->_M_manager;
622 const_cast<any*>(__any)->_M_manager = nullptr;
629 namespace __detail::__variant
631 template<typename> struct _Never_valueless_alt; // see <variant>
633 // Provide the strong exception-safety guarantee when emplacing an
634 // any into a variant.
636 struct _Never_valueless_alt<std::any>
639 } // namespace __detail::__variant
641 _GLIBCXX_END_NAMESPACE_VERSION
645 #endif // _GLIBCXX_ANY