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