You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

637 lines
18KB

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