libstdc++
any
Go to the documentation of this file.
1// <any> -*- C++ -*-
2
3// Copyright (C) 2014-2025 Free Software Foundation, Inc.
4//
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)
9// any later version.
10
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.
15
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.
19
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/>.
24
25/** @file include/any
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_ANY
30#define _GLIBCXX_ANY 1
31
32#ifdef _GLIBCXX_SYSHDR
33#pragma GCC system_header
34#endif
35
36#define __glibcxx_want_any
37#include <bits/version.h>
38
39#ifdef __cpp_lib_any // C++ >= 17
40
41#include <initializer_list>
42#include <typeinfo>
43#include <new>
44#include <type_traits>
45#include <bits/utility.h> // in_place_type_t
46
47#pragma GCC diagnostic push
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations" // aligned_storage
49
50namespace std _GLIBCXX_VISIBILITY(default)
51{
52_GLIBCXX_BEGIN_NAMESPACE_VERSION
53
54 /**
55 * @addtogroup utilities
56 * @{
57 */
58
59 /**
60 * @brief Exception class thrown by a failed @c any_cast
61 * @ingroup exceptions
62 */
63 class bad_any_cast : public bad_cast
64 {
65 public:
66 virtual const char* what() const noexcept { return "bad any_cast"; }
67 };
68
69 [[gnu::noreturn]] inline void __throw_bad_any_cast()
70 {
71#if __cpp_exceptions
72 throw bad_any_cast{};
73#else
74 __builtin_abort();
75#endif
76 }
77
78 /**
79 * @brief A type-safe container of any type.
80 *
81 * An `any` object's state is either empty or it stores a contained object
82 * of CopyConstructible type.
83 *
84 * @since C++17
85 */
86 class any
87 {
88 // Holds either pointer to a heap object or the contained object itself.
89 union _Storage
90 {
91 constexpr _Storage() : _M_ptr{nullptr} {}
92
93 // Prevent trivial copies of this type, buffer might hold a non-POD.
94 _Storage(const _Storage&) = delete;
95 _Storage& operator=(const _Storage&) = delete;
96
97 void* _M_ptr;
98 unsigned char _M_buffer[sizeof(_M_ptr)];
99 };
100
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>;
105
106 template<typename _Tp>
107 struct _Manager_internal; // uses small-object optimization
108
109 template<typename _Tp>
110 struct _Manager_external; // creates contained object on the heap
111
112 template<typename _Tp>
113 using _Manager = __conditional_t<_Internal<_Tp>::value,
114 _Manager_internal<_Tp>,
115 _Manager_external<_Tp>>;
116
117 template<typename _Tp, typename _VTp = decay_t<_Tp>>
118 using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
119
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)
124 {
125 reset();
126 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
127 _M_manager = &_Mgr::_S_manage;
128 }
129
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)
135 {
136 reset();
137 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
138 _M_manager = &_Mgr::_S_manage;
139 }
140
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,
145 _Res>;
146
147 template <typename _Tp, typename... _Args>
148 using __any_constructible_t
149 = typename __any_constructible<bool, _Tp, _Args...>::type;
150
151 template<typename _VTp, typename... _Args>
152 using __emplace_t
153 = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
154
155 public:
156 // construct/destruct
157
158 /// Default constructor, creates an empty object.
159 constexpr any() noexcept : _M_manager(nullptr) { }
160
161 /// Copy constructor, copies the state of @p __other
162 any(const any& __other)
163 {
164 if (!__other.has_value())
165 _M_manager = nullptr;
166 else
167 {
168 _Arg __arg;
169 __arg._M_any = this;
170 __other._M_manager(_Op_clone, &__other, &__arg);
171 }
172 }
173
174 /**
175 * @brief Move constructor, transfer the state from @p __other
176 *
177 * @post @c !__other.has_value() (this postcondition is a GNU extension)
178 */
179 any(any&& __other) noexcept
180 {
181 if (!__other.has_value())
182 _M_manager = nullptr;
183 else
184 {
185 _Arg __arg;
186 __arg._M_any = this;
187 __other._M_manager(_Op_xfer, &__other, &__arg);
188 }
189 }
190
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>
196 any(_Tp&& __value)
197 : _M_manager(&_Mgr::_S_manage)
198 {
199 _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
200 }
201
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>
206 explicit
207 any(in_place_type_t<_Tp>, _Args&&... __args)
208 : _M_manager(&_Mgr::_S_manage)
209 {
210 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
211 }
212
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>&,
218 _Args&&...> = false>
219 explicit
220 any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
221 : _M_manager(&_Mgr::_S_manage)
222 {
223 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
224 }
225
226 /// Destructor, calls @c reset()
227 ~any() { reset(); }
228
229 // assignments
230
231 /// Copy the state of another object.
232 any&
233 operator=(const any& __rhs)
234 {
235 *this = any(__rhs);
236 return *this;
237 }
238
239 /**
240 * @brief Move assignment operator
241 *
242 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
243 */
244 any&
245 operator=(any&& __rhs) noexcept
246 {
247 if (!__rhs.has_value())
248 reset();
249 else if (this != &__rhs)
250 {
251 reset();
252 _Arg __arg;
253 __arg._M_any = this;
254 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
255 }
256 return *this;
257 }
258
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)
263 {
264 *this = any(std::forward<_Tp>(__rhs));
265 return *this;
266 }
267
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)
272 {
273 using _VTp = decay_t<_Tp>;
274 __do_emplace<_VTp>(std::forward<_Args>(__args)...);
275 return *any::_Manager<_VTp>::_S_access(_M_storage);
276 }
277
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)
283 {
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);
287 }
288
289 // modifiers
290
291 /// If not empty, destroy the contained object.
292 void reset() noexcept
293 {
294 if (has_value())
295 {
296 _M_manager(_Op_destroy, this, nullptr);
297 _M_manager = nullptr;
298 }
299 }
300
301 /// Exchange state with another object.
302 void swap(any& __rhs) noexcept
303 {
304 if (!has_value() && !__rhs.has_value())
305 return;
306
307 if (has_value() && __rhs.has_value())
308 {
309 if (this == &__rhs)
310 return;
311
312 any __tmp;
313 _Arg __arg;
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);
318 __arg._M_any = this;
319 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
320 }
321 else
322 {
323 any* __empty = !has_value() ? this : &__rhs;
324 any* __full = !has_value() ? &__rhs : this;
325 _Arg __arg;
326 __arg._M_any = __empty;
327 __full->_M_manager(_Op_xfer, __full, &__arg);
328 }
329 }
330
331 // observers
332
333 /// Reports whether there is a contained object or not.
334 bool has_value() const noexcept { return _M_manager != nullptr; }
335
336#if __cpp_rtti
337 /// The @c typeid of the contained object, or @c typeid(void) if empty.
338 const type_info& type() const noexcept
339 {
340 if (!has_value())
341 return typeid(void);
342 _Arg __arg;
343 _M_manager(_Op_get_type_info, this, &__arg);
344 return *__arg._M_typeinfo;
345 }
346#endif
347
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; }
352 /// @endcond
353
354 private:
355 enum _Op {
356 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
357 };
358
359 union _Arg
360 {
361 void* _M_obj;
362 const std::type_info* _M_typeinfo;
363 any* _M_any;
364 };
365
366 void (*_M_manager)(_Op, const any*, _Arg*);
367 _Storage _M_storage;
368
369 /// @cond undocumented
370 template<typename _Tp>
371 friend void* __any_caster(const any* __any);
372 /// @endcond
373
374 // Manage in-place contained object.
375 template<typename _Tp>
376 struct _Manager_internal
377 {
378 static void
379 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
380
381 template<typename _Up>
382 static void
383 _S_create(_Storage& __storage, _Up&& __value)
384 {
385 void* __addr = &__storage._M_buffer;
386 ::new (__addr) _Tp(std::forward<_Up>(__value));
387 }
388
389 template<typename... _Args>
390 static void
391 _S_create(_Storage& __storage, _Args&&... __args)
392 {
393 void* __addr = &__storage._M_buffer;
394 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
395 }
396
397 static _Tp*
398 _S_access(const _Storage& __storage)
399 {
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));
403 }
404 };
405
406 // Manage external contained object.
407 template<typename _Tp>
408 struct _Manager_external
409 {
410 static void
411 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
412
413 template<typename _Up>
414 static void
415 _S_create(_Storage& __storage, _Up&& __value)
416 {
417 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
418 }
419 template<typename... _Args>
420 static void
421 _S_create(_Storage& __storage, _Args&&... __args)
422 {
423 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
424 }
425 static _Tp*
426 _S_access(const _Storage& __storage)
427 {
428 // The contained object is in *__storage._M_ptr
429 return static_cast<_Tp*>(__storage._M_ptr);
430 }
431 };
432 };
433
434 /// Exchange the states of two @c any objects.
435 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
436
437 /// Create an `any` holding a `_Tp` constructed from `__args...`.
438 template <typename _Tp, typename... _Args>
439 inline
440 enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>, _Args...>, any>
441 make_any(_Args&&... __args)
442 {
443 return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
444 }
445
446 /// Create an `any` holding a `_Tp` constructed from `__il` and `__args...`.
447 template <typename _Tp, typename _Up, typename... _Args>
448 inline
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)
452 {
453 return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
454 }
455
456 /**
457 * @brief Access the contained object.
458 *
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>)
464 * </code>
465 */
466 template<typename _ValueType>
467 inline _ValueType any_cast(const any& __any)
468 {
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);
475 if (__p)
476 return static_cast<_ValueType>(*__p);
477 __throw_bad_any_cast();
478 }
479
480 /**
481 * @brief Access the contained object.
482 *
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>)
488 * </code>
489 *
490 * @{
491 */
492 template<typename _ValueType>
493 inline _ValueType any_cast(any& __any)
494 {
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);
501 if (__p)
502 return static_cast<_ValueType>(*__p);
503 __throw_bad_any_cast();
504 }
505
506 template<typename _ValueType>
507 inline _ValueType any_cast(any&& __any)
508 {
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);
515 if (__p)
516 return static_cast<_ValueType>(std::move(*__p));
517 __throw_bad_any_cast();
518 }
519 /// @}
520
521 /// @cond undocumented
522 template<typename _Tp>
523 void* __any_caster(const any* __any)
524 {
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>)
531 return nullptr;
532 // Only copy constructible types can be used for contained values:
533 else if constexpr (!is_copy_constructible_v<_Up>)
534 return nullptr;
535 // First try comparing function addresses, which works without RTTI
536 else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
537#if __cpp_rtti
538 || __any->type() == typeid(_Tp)
539#endif
540 )
541 {
542 return any::_Manager<_Up>::_S_access(__any->_M_storage);
543 }
544 return nullptr;
545 }
546 /// @endcond
547
548 /**
549 * @brief Access the contained object.
550 *
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.
556 *
557 * @{
558 */
559 template<typename _ValueType>
560 inline const _ValueType* any_cast(const any* __any) noexcept
561 {
562 // _GLIBCXX_RESOLVE_LIB_DEFECTS
563 // 3305. any_cast<void>
564 static_assert(!is_void_v<_ValueType>);
565
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>)
569 if (__any)
570 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
571 return nullptr;
572 }
573
574 template<typename _ValueType>
575 inline _ValueType* any_cast(any* __any) noexcept
576 {
577 static_assert(!is_void_v<_ValueType>);
578
579 if constexpr (is_object_v<_ValueType>)
580 if (__any)
581 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
582 return nullptr;
583 }
584 /// @}
585
586 template<typename _Tp>
587 void
588 any::_Manager_internal<_Tp>::
589 _S_manage(_Op __which, const any* __any, _Arg* __arg)
590 {
591 // The contained object is in _M_storage._M_buffer
592 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
593 switch (__which)
594 {
595 case _Op_access:
596 __arg->_M_obj = const_cast<_Tp*>(__ptr);
597 break;
598 case _Op_get_type_info:
599#if __cpp_rtti
600 __arg->_M_typeinfo = &typeid(_Tp);
601#endif
602 break;
603 case _Op_clone:
604 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
605 __arg->_M_any->_M_manager = __any->_M_manager;
606 break;
607 case _Op_destroy:
608 __ptr->~_Tp();
609 break;
610 case _Op_xfer:
611 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
612 (std::move(*const_cast<_Tp*>(__ptr)));
613 __ptr->~_Tp();
614 __arg->_M_any->_M_manager = __any->_M_manager;
615 const_cast<any*>(__any)->_M_manager = nullptr;
616 break;
617 }
618 }
619
620 template<typename _Tp>
621 void
622 any::_Manager_external<_Tp>::
623 _S_manage(_Op __which, const any* __any, _Arg* __arg)
624 {
625 // The contained object is *_M_storage._M_ptr
626 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
627 switch (__which)
628 {
629 case _Op_access:
630 __arg->_M_obj = const_cast<_Tp*>(__ptr);
631 break;
632 case _Op_get_type_info:
633#if __cpp_rtti
634 __arg->_M_typeinfo = &typeid(_Tp);
635#endif
636 break;
637 case _Op_clone:
638 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
639 __arg->_M_any->_M_manager = __any->_M_manager;
640 break;
641 case _Op_destroy:
642 delete __ptr;
643 break;
644 case _Op_xfer:
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;
648 break;
649 }
650 }
651
652 /// @}
653
654 namespace __detail::__variant
655 {
656 template<typename> struct _Never_valueless_alt; // see <variant>
657
658 // Provide the strong exception-safety guarantee when emplacing an
659 // any into a variant.
660 template<>
661 struct _Never_valueless_alt<std::any>
662 : std::true_type
663 { };
664 } // namespace __detail::__variant
665
666_GLIBCXX_END_NAMESPACE_VERSION
667} // namespace std
668
669#pragma GCC diagnostic pop
670
671#endif // __cpp_lib_any
672#endif // _GLIBCXX_ANY