any 18 KB

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