any 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. // <any> -*- C++ -*-
  2. // Copyright (C) 2014-2022 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file include/any
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_ANY
  24. #define _GLIBCXX_ANY 1
  25. #pragma GCC system_header
  26. #if __cplusplus >= 201703L
  27. #include <initializer_list>
  28. #include <typeinfo>
  29. #include <new>
  30. #include <type_traits>
  31. #include <bits/utility.h> // in_place_type_t
  32. namespace std _GLIBCXX_VISIBILITY(default)
  33. {
  34. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  35. /**
  36. * @addtogroup utilities
  37. * @{
  38. */
  39. /**
  40. * @brief Exception class thrown by a failed @c any_cast
  41. * @ingroup exceptions
  42. */
  43. class bad_any_cast : public bad_cast
  44. {
  45. public:
  46. virtual const char* what() const noexcept { return "bad any_cast"; }
  47. };
  48. [[gnu::noreturn]] inline void __throw_bad_any_cast()
  49. {
  50. #if __cpp_exceptions
  51. throw bad_any_cast{};
  52. #else
  53. __builtin_abort();
  54. #endif
  55. }
  56. #define __cpp_lib_any 201606L
  57. /**
  58. * @brief A type-safe container of any type.
  59. *
  60. * An `any` object's state is either empty or it stores a contained object
  61. * of CopyConstructible type.
  62. *
  63. * @since C++17
  64. */
  65. class any
  66. {
  67. // Holds either pointer to a heap object or the contained object itself.
  68. union _Storage
  69. {
  70. constexpr _Storage() : _M_ptr{nullptr} {}
  71. // Prevent trivial copies of this type, buffer might hold a non-POD.
  72. _Storage(const _Storage&) = delete;
  73. _Storage& operator=(const _Storage&) = delete;
  74. void* _M_ptr;
  75. aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
  76. };
  77. template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
  78. bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
  79. && (alignof(_Tp) <= alignof(_Storage))>
  80. using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
  81. template<typename _Tp>
  82. struct _Manager_internal; // uses small-object optimization
  83. template<typename _Tp>
  84. struct _Manager_external; // creates contained object on the heap
  85. template<typename _Tp>
  86. using _Manager = __conditional_t<_Internal<_Tp>::value,
  87. _Manager_internal<_Tp>,
  88. _Manager_external<_Tp>>;
  89. template<typename _Tp, typename _VTp = decay_t<_Tp>>
  90. using _Decay_if_not_any = enable_if_t<!is_same_v<_VTp, any>, _VTp>;
  91. /// Emplace with an object created from @p __args as the contained object.
  92. template <typename _Tp, typename... _Args,
  93. typename _Mgr = _Manager<_Tp>>
  94. void __do_emplace(_Args&&... __args)
  95. {
  96. reset();
  97. _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
  98. _M_manager = &_Mgr::_S_manage;
  99. }
  100. /// Emplace with an object created from @p __il and @p __args as
  101. /// the contained object.
  102. template <typename _Tp, typename _Up, typename... _Args,
  103. typename _Mgr = _Manager<_Tp>>
  104. void __do_emplace(initializer_list<_Up> __il, _Args&&... __args)
  105. {
  106. reset();
  107. _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
  108. _M_manager = &_Mgr::_S_manage;
  109. }
  110. template <typename _Res, typename _Tp, typename... _Args>
  111. using __any_constructible
  112. = enable_if<__and_<is_copy_constructible<_Tp>,
  113. is_constructible<_Tp, _Args...>>::value,
  114. _Res>;
  115. template <typename _Tp, typename... _Args>
  116. using __any_constructible_t
  117. = typename __any_constructible<bool, _Tp, _Args...>::type;
  118. template<typename _VTp, typename... _Args>
  119. using __emplace_t
  120. = typename __any_constructible<_VTp&, _VTp, _Args...>::type;
  121. public:
  122. // construct/destruct
  123. /// Default constructor, creates an empty object.
  124. constexpr any() noexcept : _M_manager(nullptr) { }
  125. /// Copy constructor, copies the state of @p __other
  126. any(const any& __other)
  127. {
  128. if (!__other.has_value())
  129. _M_manager = nullptr;
  130. else
  131. {
  132. _Arg __arg;
  133. __arg._M_any = this;
  134. __other._M_manager(_Op_clone, &__other, &__arg);
  135. }
  136. }
  137. /**
  138. * @brief Move constructor, transfer the state from @p __other
  139. *
  140. * @post @c !__other.has_value() (this postcondition is a GNU extension)
  141. */
  142. any(any&& __other) noexcept
  143. {
  144. if (!__other.has_value())
  145. _M_manager = nullptr;
  146. else
  147. {
  148. _Arg __arg;
  149. __arg._M_any = this;
  150. __other._M_manager(_Op_xfer, &__other, &__arg);
  151. }
  152. }
  153. /// Construct with a copy of @p __value as the contained object.
  154. template <typename _Tp, typename _VTp = _Decay_if_not_any<_Tp>,
  155. typename _Mgr = _Manager<_VTp>,
  156. enable_if_t<is_copy_constructible_v<_VTp>
  157. && !__is_in_place_type_v<_VTp>, bool> = true>
  158. any(_Tp&& __value)
  159. : _M_manager(&_Mgr::_S_manage)
  160. {
  161. _Mgr::_S_create(_M_storage, std::forward<_Tp>(__value));
  162. }
  163. /// Construct with an object created from @p __args as the contained object.
  164. template <typename _Tp, typename... _Args, typename _VTp = decay_t<_Tp>,
  165. typename _Mgr = _Manager<_VTp>,
  166. __any_constructible_t<_VTp, _Args&&...> = false>
  167. explicit
  168. any(in_place_type_t<_Tp>, _Args&&... __args)
  169. : _M_manager(&_Mgr::_S_manage)
  170. {
  171. _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
  172. }
  173. /// Construct with an object created from @p __il and @p __args as
  174. /// the contained object.
  175. template <typename _Tp, typename _Up, typename... _Args,
  176. typename _VTp = decay_t<_Tp>, typename _Mgr = _Manager<_VTp>,
  177. __any_constructible_t<_VTp, initializer_list<_Up>&,
  178. _Args&&...> = false>
  179. explicit
  180. any(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args)
  181. : _M_manager(&_Mgr::_S_manage)
  182. {
  183. _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
  184. }
  185. /// Destructor, calls @c reset()
  186. ~any() { reset(); }
  187. // assignments
  188. /// Copy the state of another object.
  189. any&
  190. operator=(const any& __rhs)
  191. {
  192. *this = any(__rhs);
  193. return *this;
  194. }
  195. /**
  196. * @brief Move assignment operator
  197. *
  198. * @post @c !__rhs.has_value() (not guaranteed for other implementations)
  199. */
  200. any&
  201. operator=(any&& __rhs) noexcept
  202. {
  203. if (!__rhs.has_value())
  204. reset();
  205. else if (this != &__rhs)
  206. {
  207. reset();
  208. _Arg __arg;
  209. __arg._M_any = this;
  210. __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
  211. }
  212. return *this;
  213. }
  214. /// Store a copy of @p __rhs as the contained object.
  215. template<typename _Tp>
  216. enable_if_t<is_copy_constructible<_Decay_if_not_any<_Tp>>::value, any&>
  217. operator=(_Tp&& __rhs)
  218. {
  219. *this = any(std::forward<_Tp>(__rhs));
  220. return *this;
  221. }
  222. /// Emplace with an object created from @p __args as the contained object.
  223. template <typename _Tp, typename... _Args>
  224. __emplace_t<decay_t<_Tp>, _Args...>
  225. emplace(_Args&&... __args)
  226. {
  227. using _VTp = decay_t<_Tp>;
  228. __do_emplace<_VTp>(std::forward<_Args>(__args)...);
  229. return *any::_Manager<_VTp>::_S_access(_M_storage);
  230. }
  231. /// Emplace with an object created from @p __il and @p __args as
  232. /// the contained object.
  233. template <typename _Tp, typename _Up, typename... _Args>
  234. __emplace_t<decay_t<_Tp>, initializer_list<_Up>&, _Args&&...>
  235. emplace(initializer_list<_Up> __il, _Args&&... __args)
  236. {
  237. using _VTp = decay_t<_Tp>;
  238. __do_emplace<_VTp, _Up>(__il, std::forward<_Args>(__args)...);
  239. return *any::_Manager<_VTp>::_S_access(_M_storage);
  240. }
  241. // modifiers
  242. /// If not empty, destroy the contained object.
  243. void reset() noexcept
  244. {
  245. if (has_value())
  246. {
  247. _M_manager(_Op_destroy, this, nullptr);
  248. _M_manager = nullptr;
  249. }
  250. }
  251. /// Exchange state with another object.
  252. void swap(any& __rhs) noexcept
  253. {
  254. if (!has_value() && !__rhs.has_value())
  255. return;
  256. if (has_value() && __rhs.has_value())
  257. {
  258. if (this == &__rhs)
  259. return;
  260. any __tmp;
  261. _Arg __arg;
  262. __arg._M_any = &__tmp;
  263. __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
  264. __arg._M_any = &__rhs;
  265. _M_manager(_Op_xfer, this, &__arg);
  266. __arg._M_any = this;
  267. __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
  268. }
  269. else
  270. {
  271. any* __empty = !has_value() ? this : &__rhs;
  272. any* __full = !has_value() ? &__rhs : this;
  273. _Arg __arg;
  274. __arg._M_any = __empty;
  275. __full->_M_manager(_Op_xfer, __full, &__arg);
  276. }
  277. }
  278. // observers
  279. /// Reports whether there is a contained object or not.
  280. bool has_value() const noexcept { return _M_manager != nullptr; }
  281. #if __cpp_rtti
  282. /// The @c typeid of the contained object, or @c typeid(void) if empty.
  283. const type_info& type() const noexcept
  284. {
  285. if (!has_value())
  286. return typeid(void);
  287. _Arg __arg;
  288. _M_manager(_Op_get_type_info, this, &__arg);
  289. return *__arg._M_typeinfo;
  290. }
  291. #endif
  292. /// @cond undocumented
  293. template<typename _Tp>
  294. static constexpr bool __is_valid_cast()
  295. { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
  296. /// @endcond
  297. private:
  298. enum _Op {
  299. _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
  300. };
  301. union _Arg
  302. {
  303. void* _M_obj;
  304. const std::type_info* _M_typeinfo;
  305. any* _M_any;
  306. };
  307. void (*_M_manager)(_Op, const any*, _Arg*);
  308. _Storage _M_storage;
  309. /// @cond undocumented
  310. template<typename _Tp>
  311. friend void* __any_caster(const any* __any);
  312. /// @endcond
  313. // Manage in-place contained object.
  314. template<typename _Tp>
  315. struct _Manager_internal
  316. {
  317. static void
  318. _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
  319. template<typename _Up>
  320. static void
  321. _S_create(_Storage& __storage, _Up&& __value)
  322. {
  323. void* __addr = &__storage._M_buffer;
  324. ::new (__addr) _Tp(std::forward<_Up>(__value));
  325. }
  326. template<typename... _Args>
  327. static void
  328. _S_create(_Storage& __storage, _Args&&... __args)
  329. {
  330. void* __addr = &__storage._M_buffer;
  331. ::new (__addr) _Tp(std::forward<_Args>(__args)...);
  332. }
  333. static _Tp*
  334. _S_access(const _Storage& __storage)
  335. {
  336. // The contained object is in __storage._M_buffer
  337. const void* __addr = &__storage._M_buffer;
  338. return static_cast<_Tp*>(const_cast<void*>(__addr));
  339. }
  340. };
  341. // Manage external contained object.
  342. template<typename _Tp>
  343. struct _Manager_external
  344. {
  345. static void
  346. _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
  347. template<typename _Up>
  348. static void
  349. _S_create(_Storage& __storage, _Up&& __value)
  350. {
  351. __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
  352. }
  353. template<typename... _Args>
  354. static void
  355. _S_create(_Storage& __storage, _Args&&... __args)
  356. {
  357. __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
  358. }
  359. static _Tp*
  360. _S_access(const _Storage& __storage)
  361. {
  362. // The contained object is in *__storage._M_ptr
  363. return static_cast<_Tp*>(__storage._M_ptr);
  364. }
  365. };
  366. };
  367. /// Exchange the states of two @c any objects.
  368. inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
  369. /// Create an `any` holding a `_Tp` constructed from `__args...`.
  370. template <typename _Tp, typename... _Args>
  371. inline
  372. enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>, _Args...>, any>
  373. make_any(_Args&&... __args)
  374. {
  375. return any(in_place_type<_Tp>, std::forward<_Args>(__args)...);
  376. }
  377. /// Create an `any` holding a `_Tp` constructed from `__il` and `__args...`.
  378. template <typename _Tp, typename _Up, typename... _Args>
  379. inline
  380. enable_if_t<is_constructible_v<any, in_place_type_t<_Tp>,
  381. initializer_list<_Up>&, _Args...>, any>
  382. make_any(initializer_list<_Up> __il, _Args&&... __args)
  383. {
  384. return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...);
  385. }
  386. /**
  387. * @brief Access the contained object.
  388. *
  389. * @tparam _ValueType A const-reference or CopyConstructible type.
  390. * @param __any The object to access.
  391. * @return The contained object.
  392. * @throw bad_any_cast If <code>
  393. * __any.type() != typeid(remove_reference_t<_ValueType>)
  394. * </code>
  395. */
  396. template<typename _ValueType>
  397. inline _ValueType any_cast(const any& __any)
  398. {
  399. using _Up = __remove_cvref_t<_ValueType>;
  400. static_assert(any::__is_valid_cast<_ValueType>(),
  401. "Template argument must be a reference or CopyConstructible type");
  402. static_assert(is_constructible_v<_ValueType, const _Up&>,
  403. "Template argument must be constructible from a const value.");
  404. auto __p = any_cast<_Up>(&__any);
  405. if (__p)
  406. return static_cast<_ValueType>(*__p);
  407. __throw_bad_any_cast();
  408. }
  409. /**
  410. * @brief Access the contained object.
  411. *
  412. * @tparam _ValueType A reference or CopyConstructible type.
  413. * @param __any The object to access.
  414. * @return The contained object.
  415. * @throw bad_any_cast If <code>
  416. * __any.type() != typeid(remove_reference_t<_ValueType>)
  417. * </code>
  418. *
  419. * @{
  420. */
  421. template<typename _ValueType>
  422. inline _ValueType any_cast(any& __any)
  423. {
  424. using _Up = __remove_cvref_t<_ValueType>;
  425. static_assert(any::__is_valid_cast<_ValueType>(),
  426. "Template argument must be a reference or CopyConstructible type");
  427. static_assert(is_constructible_v<_ValueType, _Up&>,
  428. "Template argument must be constructible from an lvalue.");
  429. auto __p = any_cast<_Up>(&__any);
  430. if (__p)
  431. return static_cast<_ValueType>(*__p);
  432. __throw_bad_any_cast();
  433. }
  434. template<typename _ValueType>
  435. inline _ValueType any_cast(any&& __any)
  436. {
  437. using _Up = __remove_cvref_t<_ValueType>;
  438. static_assert(any::__is_valid_cast<_ValueType>(),
  439. "Template argument must be a reference or CopyConstructible type");
  440. static_assert(is_constructible_v<_ValueType, _Up>,
  441. "Template argument must be constructible from an rvalue.");
  442. auto __p = any_cast<_Up>(&__any);
  443. if (__p)
  444. return static_cast<_ValueType>(std::move(*__p));
  445. __throw_bad_any_cast();
  446. }
  447. /// @}
  448. /// @cond undocumented
  449. template<typename _Tp>
  450. void* __any_caster(const any* __any)
  451. {
  452. // any_cast<T> returns non-null if __any->type() == typeid(T) and
  453. // typeid(T) ignores cv-qualifiers so remove them:
  454. using _Up = remove_cv_t<_Tp>;
  455. // The contained value has a decayed type, so if decay_t<U> is not U,
  456. // then it's not possible to have a contained value of type U:
  457. if constexpr (!is_same_v<decay_t<_Up>, _Up>)
  458. return nullptr;
  459. // Only copy constructible types can be used for contained values:
  460. else if constexpr (!is_copy_constructible_v<_Up>)
  461. return nullptr;
  462. // First try comparing function addresses, which works without RTTI
  463. else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
  464. #if __cpp_rtti
  465. || __any->type() == typeid(_Tp)
  466. #endif
  467. )
  468. {
  469. return any::_Manager<_Up>::_S_access(__any->_M_storage);
  470. }
  471. return nullptr;
  472. }
  473. /// @endcond
  474. /**
  475. * @brief Access the contained object.
  476. *
  477. * @tparam _ValueType The type of the contained object.
  478. * @param __any A pointer to the object to access.
  479. * @return The address of the contained object if <code>
  480. * __any != nullptr && __any.type() == typeid(_ValueType)
  481. * </code>, otherwise a null pointer.
  482. *
  483. * @{
  484. */
  485. template<typename _ValueType>
  486. inline const _ValueType* any_cast(const any* __any) noexcept
  487. {
  488. if constexpr (is_object_v<_ValueType>)
  489. if (__any)
  490. return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
  491. return nullptr;
  492. }
  493. template<typename _ValueType>
  494. inline _ValueType* any_cast(any* __any) noexcept
  495. {
  496. if constexpr (is_object_v<_ValueType>)
  497. if (__any)
  498. return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
  499. return nullptr;
  500. }
  501. /// @}
  502. template<typename _Tp>
  503. void
  504. any::_Manager_internal<_Tp>::
  505. _S_manage(_Op __which, const any* __any, _Arg* __arg)
  506. {
  507. // The contained object is in _M_storage._M_buffer
  508. auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
  509. switch (__which)
  510. {
  511. case _Op_access:
  512. __arg->_M_obj = const_cast<_Tp*>(__ptr);
  513. break;
  514. case _Op_get_type_info:
  515. #if __cpp_rtti
  516. __arg->_M_typeinfo = &typeid(_Tp);
  517. #endif
  518. break;
  519. case _Op_clone:
  520. ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
  521. __arg->_M_any->_M_manager = __any->_M_manager;
  522. break;
  523. case _Op_destroy:
  524. __ptr->~_Tp();
  525. break;
  526. case _Op_xfer:
  527. ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
  528. (std::move(*const_cast<_Tp*>(__ptr)));
  529. __ptr->~_Tp();
  530. __arg->_M_any->_M_manager = __any->_M_manager;
  531. const_cast<any*>(__any)->_M_manager = nullptr;
  532. break;
  533. }
  534. }
  535. template<typename _Tp>
  536. void
  537. any::_Manager_external<_Tp>::
  538. _S_manage(_Op __which, const any* __any, _Arg* __arg)
  539. {
  540. // The contained object is *_M_storage._M_ptr
  541. auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
  542. switch (__which)
  543. {
  544. case _Op_access:
  545. __arg->_M_obj = const_cast<_Tp*>(__ptr);
  546. break;
  547. case _Op_get_type_info:
  548. #if __cpp_rtti
  549. __arg->_M_typeinfo = &typeid(_Tp);
  550. #endif
  551. break;
  552. case _Op_clone:
  553. __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
  554. __arg->_M_any->_M_manager = __any->_M_manager;
  555. break;
  556. case _Op_destroy:
  557. delete __ptr;
  558. break;
  559. case _Op_xfer:
  560. __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
  561. __arg->_M_any->_M_manager = __any->_M_manager;
  562. const_cast<any*>(__any)->_M_manager = nullptr;
  563. break;
  564. }
  565. }
  566. /// @}
  567. namespace __detail::__variant
  568. {
  569. template<typename> struct _Never_valueless_alt; // see <variant>
  570. // Provide the strong exception-safety guarantee when emplacing an
  571. // any into a variant.
  572. template<>
  573. struct _Never_valueless_alt<std::any>
  574. : std::true_type
  575. { };
  576. } // namespace __detail::__variant
  577. _GLIBCXX_END_NAMESPACE_VERSION
  578. } // namespace std
  579. #endif // C++17
  580. #endif // _GLIBCXX_ANY