any 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. // <experimental/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 experimental/any
  21. * This is a TS C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_EXPERIMENTAL_ANY
  24. #define _GLIBCXX_EXPERIMENTAL_ANY 1
  25. #pragma GCC system_header
  26. #if __cplusplus >= 201402L
  27. #include <typeinfo>
  28. #include <new>
  29. #include <utility>
  30. #include <type_traits>
  31. #include <experimental/bits/lfts_config.h>
  32. namespace std _GLIBCXX_VISIBILITY(default)
  33. {
  34. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  35. namespace experimental
  36. {
  37. inline namespace fundamentals_v1
  38. {
  39. /**
  40. * @defgroup any Type-safe container of any type
  41. * @ingroup experimental
  42. *
  43. * A type-safe container for single values of value types, as
  44. * described in n3804 "Any Library Proposal (Revision 3)".
  45. *
  46. * @{
  47. */
  48. #define __cpp_lib_experimental_any 201411
  49. /**
  50. * @brief Exception class thrown by a failed @c any_cast
  51. * @ingroup exceptions
  52. */
  53. class bad_any_cast : public bad_cast
  54. {
  55. public:
  56. virtual const char* what() const noexcept { return "bad any_cast"; }
  57. };
  58. [[gnu::noreturn]] inline void __throw_bad_any_cast()
  59. {
  60. #if __cpp_exceptions
  61. throw bad_any_cast{};
  62. #else
  63. __builtin_abort();
  64. #endif
  65. }
  66. /**
  67. * @brief A type-safe container of any type.
  68. *
  69. * An @c any object's state is either empty or it stores a contained object
  70. * of CopyConstructible type.
  71. */
  72. class any
  73. {
  74. // Holds either pointer to a heap object or the contained object itself.
  75. union _Storage
  76. {
  77. // This constructor intentionally doesn't initialize anything.
  78. _Storage() = default;
  79. // Prevent trivial copies of this type, buffer might hold a non-POD.
  80. _Storage(const _Storage&) = delete;
  81. _Storage& operator=(const _Storage&) = delete;
  82. void* _M_ptr;
  83. aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
  84. };
  85. template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
  86. bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
  87. && (alignof(_Tp) <= alignof(_Storage))>
  88. using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
  89. template<typename _Tp>
  90. struct _Manager_internal; // uses small-object optimization
  91. template<typename _Tp>
  92. struct _Manager_external; // creates contained object on the heap
  93. template<typename _Tp>
  94. using _Manager = conditional_t<_Internal<_Tp>::value,
  95. _Manager_internal<_Tp>,
  96. _Manager_external<_Tp>>;
  97. template<typename _Tp, typename _Decayed = decay_t<_Tp>>
  98. using _Decay = enable_if_t<!is_same<_Decayed, any>::value, _Decayed>;
  99. public:
  100. // construct/destruct
  101. /// Default constructor, creates an empty object.
  102. any() noexcept : _M_manager(nullptr) { }
  103. /// Copy constructor, copies the state of @p __other
  104. any(const any& __other)
  105. {
  106. if (__other.empty())
  107. _M_manager = nullptr;
  108. else
  109. {
  110. _Arg __arg;
  111. __arg._M_any = this;
  112. __other._M_manager(_Op_clone, &__other, &__arg);
  113. }
  114. }
  115. /**
  116. * @brief Move constructor, transfer the state from @p __other
  117. *
  118. * @post @c __other.empty() (this postcondition is a GNU extension)
  119. */
  120. any(any&& __other) noexcept
  121. {
  122. if (__other.empty())
  123. _M_manager = nullptr;
  124. else
  125. {
  126. _Arg __arg;
  127. __arg._M_any = this;
  128. __other._M_manager(_Op_xfer, &__other, &__arg);
  129. }
  130. }
  131. /// Construct with a copy of @p __value as the contained object.
  132. template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
  133. typename _Mgr = _Manager<_Tp>,
  134. typename enable_if<is_constructible<_Tp, _ValueType&&>::value,
  135. bool>::type = true>
  136. any(_ValueType&& __value)
  137. : _M_manager(&_Mgr::_S_manage)
  138. {
  139. _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value));
  140. static_assert(is_copy_constructible<_Tp>::value,
  141. "The contained object must be CopyConstructible");
  142. }
  143. /// Construct with a copy of @p __value as the contained object.
  144. template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
  145. typename _Mgr = _Manager<_Tp>,
  146. typename enable_if<!is_constructible<_Tp, _ValueType&&>::value,
  147. bool>::type = false>
  148. any(_ValueType&& __value)
  149. : _M_manager(&_Mgr::_S_manage)
  150. {
  151. _Mgr::_S_create(_M_storage, __value);
  152. static_assert(is_copy_constructible<_Tp>::value,
  153. "The contained object must be CopyConstructible");
  154. }
  155. /// Destructor, calls @c clear()
  156. ~any() { clear(); }
  157. // assignments
  158. /// Copy the state of another object.
  159. any& operator=(const any& __rhs)
  160. {
  161. *this = any(__rhs);
  162. return *this;
  163. }
  164. /**
  165. * @brief Move assignment operator
  166. *
  167. * @post @c __rhs.empty() (not guaranteed for other implementations)
  168. */
  169. any& operator=(any&& __rhs) noexcept
  170. {
  171. if (__rhs.empty())
  172. clear();
  173. else if (this != &__rhs)
  174. {
  175. clear();
  176. _Arg __arg;
  177. __arg._M_any = this;
  178. __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
  179. }
  180. return *this;
  181. }
  182. /// Store a copy of @p __rhs as the contained object.
  183. template<typename _ValueType>
  184. enable_if_t<!is_same<any, decay_t<_ValueType>>::value, any&>
  185. operator=(_ValueType&& __rhs)
  186. {
  187. *this = any(std::forward<_ValueType>(__rhs));
  188. return *this;
  189. }
  190. // modifiers
  191. /// If not empty, destroy the contained object.
  192. void clear() noexcept
  193. {
  194. if (!empty())
  195. {
  196. _M_manager(_Op_destroy, this, nullptr);
  197. _M_manager = nullptr;
  198. }
  199. }
  200. /// Exchange state with another object.
  201. void swap(any& __rhs) noexcept
  202. {
  203. if (empty() && __rhs.empty())
  204. return;
  205. if (!empty() && !__rhs.empty())
  206. {
  207. if (this == &__rhs)
  208. return;
  209. any __tmp;
  210. _Arg __arg;
  211. __arg._M_any = &__tmp;
  212. __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
  213. __arg._M_any = &__rhs;
  214. _M_manager(_Op_xfer, this, &__arg);
  215. __arg._M_any = this;
  216. __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
  217. }
  218. else
  219. {
  220. any* __empty = empty() ? this : &__rhs;
  221. any* __full = empty() ? &__rhs : this;
  222. _Arg __arg;
  223. __arg._M_any = __empty;
  224. __full->_M_manager(_Op_xfer, __full, &__arg);
  225. }
  226. }
  227. // observers
  228. /// Reports whether there is a contained object or not.
  229. _GLIBCXX_NODISCARD bool empty() const noexcept { return _M_manager == nullptr; }
  230. #if __cpp_rtti
  231. /// The @c typeid of the contained object, or @c typeid(void) if empty.
  232. const type_info& type() const noexcept
  233. {
  234. if (empty())
  235. return typeid(void);
  236. _Arg __arg;
  237. _M_manager(_Op_get_type_info, this, &__arg);
  238. return *__arg._M_typeinfo;
  239. }
  240. #endif
  241. template<typename _Tp>
  242. static constexpr bool __is_valid_cast()
  243. { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
  244. private:
  245. enum _Op {
  246. _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
  247. };
  248. union _Arg
  249. {
  250. void* _M_obj;
  251. const std::type_info* _M_typeinfo;
  252. any* _M_any;
  253. };
  254. void (*_M_manager)(_Op, const any*, _Arg*);
  255. _Storage _M_storage;
  256. template<typename _Tp>
  257. friend enable_if_t<is_object<_Tp>::value, void*>
  258. __any_caster(const any* __any);
  259. // Manage in-place contained object.
  260. template<typename _Tp>
  261. struct _Manager_internal
  262. {
  263. static void
  264. _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
  265. template<typename _Up>
  266. static void
  267. _S_create(_Storage& __storage, _Up&& __value)
  268. {
  269. void* __addr = &__storage._M_buffer;
  270. ::new (__addr) _Tp(std::forward<_Up>(__value));
  271. }
  272. };
  273. // Manage external contained object.
  274. template<typename _Tp>
  275. struct _Manager_external
  276. {
  277. static void
  278. _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
  279. template<typename _Up>
  280. static void
  281. _S_create(_Storage& __storage, _Up&& __value)
  282. {
  283. __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
  284. }
  285. };
  286. };
  287. /// Exchange the states of two @c any objects.
  288. inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
  289. /**
  290. * @brief Access the contained object.
  291. *
  292. * @tparam _ValueType A const-reference or CopyConstructible type.
  293. * @param __any The object to access.
  294. * @return The contained object.
  295. * @throw bad_any_cast If <code>
  296. * __any.type() != typeid(remove_reference_t<_ValueType>)
  297. * </code>
  298. */
  299. template<typename _ValueType>
  300. inline _ValueType any_cast(const any& __any)
  301. {
  302. static_assert(any::__is_valid_cast<_ValueType>(),
  303. "Template argument must be a reference or CopyConstructible type");
  304. auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
  305. if (__p)
  306. return *__p;
  307. __throw_bad_any_cast();
  308. }
  309. /**
  310. * @brief Access the contained object.
  311. *
  312. * @tparam _ValueType A reference or CopyConstructible type.
  313. * @param __any The object to access.
  314. * @return The contained object.
  315. * @throw bad_any_cast If <code>
  316. * __any.type() != typeid(remove_reference_t<_ValueType>)
  317. * </code>
  318. *
  319. * @{
  320. */
  321. template<typename _ValueType>
  322. inline _ValueType any_cast(any& __any)
  323. {
  324. static_assert(any::__is_valid_cast<_ValueType>(),
  325. "Template argument must be a reference or CopyConstructible type");
  326. auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
  327. if (__p)
  328. return *__p;
  329. __throw_bad_any_cast();
  330. }
  331. template<typename _ValueType,
  332. typename enable_if<!is_move_constructible<_ValueType>::value
  333. || is_lvalue_reference<_ValueType>::value,
  334. bool>::type = true>
  335. inline _ValueType any_cast(any&& __any)
  336. {
  337. static_assert(any::__is_valid_cast<_ValueType>(),
  338. "Template argument must be a reference or CopyConstructible type");
  339. auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
  340. if (__p)
  341. return *__p;
  342. __throw_bad_any_cast();
  343. }
  344. template<typename _ValueType,
  345. typename enable_if<is_move_constructible<_ValueType>::value
  346. && !is_lvalue_reference<_ValueType>::value,
  347. bool>::type = false>
  348. inline _ValueType any_cast(any&& __any)
  349. {
  350. static_assert(any::__is_valid_cast<_ValueType>(),
  351. "Template argument must be a reference or CopyConstructible type");
  352. auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
  353. if (__p)
  354. return std::move(*__p);
  355. __throw_bad_any_cast();
  356. }
  357. // @}
  358. /// @cond undocumented
  359. template<typename _Tp>
  360. enable_if_t<is_object<_Tp>::value, void*>
  361. __any_caster(const any* __any)
  362. {
  363. // any_cast<T> returns non-null if __any->type() == typeid(T) and
  364. // typeid(T) ignores cv-qualifiers so remove them:
  365. using _Up = remove_cv_t<_Tp>;
  366. // The contained value has a decayed type, so if decay_t<U> is not U,
  367. // then it's not possible to have a contained value of type U.
  368. using __does_not_decay = is_same<decay_t<_Up>, _Up>;
  369. // Only copy constructible types can be used for contained values.
  370. using __is_copyable = is_copy_constructible<_Up>;
  371. // If the type _Tp could never be stored in an any we don't want to
  372. // instantiate _Manager<_Tp>, so use _Manager<any::_Op> instead, which
  373. // is explicitly specialized and has a no-op _S_manage function.
  374. using _Vp = conditional_t<__and_<__does_not_decay, __is_copyable>::value,
  375. _Up, any::_Op>;
  376. // First try comparing function addresses, which works without RTTI
  377. if (__any->_M_manager == &any::_Manager<_Vp>::_S_manage
  378. #if __cpp_rtti
  379. || __any->type() == typeid(_Tp)
  380. #endif
  381. )
  382. {
  383. any::_Arg __arg;
  384. __any->_M_manager(any::_Op_access, __any, &__arg);
  385. return __arg._M_obj;
  386. }
  387. return nullptr;
  388. }
  389. // This overload exists so that std::any_cast<void(*)()>(a) is well-formed.
  390. template<typename _Tp>
  391. enable_if_t<!is_object<_Tp>::value, _Tp*>
  392. __any_caster(const any*) noexcept
  393. { return nullptr; }
  394. /// @endcond
  395. /**
  396. * @brief Access the contained object.
  397. *
  398. * @tparam _ValueType The type of the contained object.
  399. * @param __any A pointer to the object to access.
  400. * @return The address of the contained object if <code>
  401. * __any != nullptr && __any.type() == typeid(_ValueType)
  402. * </code>, otherwise a null pointer.
  403. *
  404. * @{
  405. */
  406. template<typename _ValueType>
  407. inline const _ValueType* any_cast(const any* __any) noexcept
  408. {
  409. if (__any)
  410. return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
  411. return nullptr;
  412. }
  413. template<typename _ValueType>
  414. inline _ValueType* any_cast(any* __any) noexcept
  415. {
  416. if (__any)
  417. return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
  418. return nullptr;
  419. }
  420. // @}
  421. template<typename _Tp>
  422. void
  423. any::_Manager_internal<_Tp>::
  424. _S_manage(_Op __which, const any* __any, _Arg* __arg)
  425. {
  426. // The contained object is in _M_storage._M_buffer
  427. auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
  428. switch (__which)
  429. {
  430. case _Op_access:
  431. __arg->_M_obj = const_cast<_Tp*>(__ptr);
  432. break;
  433. case _Op_get_type_info:
  434. #if __cpp_rtti
  435. __arg->_M_typeinfo = &typeid(_Tp);
  436. #endif
  437. break;
  438. case _Op_clone:
  439. ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
  440. __arg->_M_any->_M_manager = __any->_M_manager;
  441. break;
  442. case _Op_destroy:
  443. __ptr->~_Tp();
  444. break;
  445. case _Op_xfer:
  446. ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
  447. (std::move(*const_cast<_Tp*>(__ptr)));
  448. __ptr->~_Tp();
  449. __arg->_M_any->_M_manager = __any->_M_manager;
  450. const_cast<any*>(__any)->_M_manager = nullptr;
  451. break;
  452. }
  453. }
  454. template<typename _Tp>
  455. void
  456. any::_Manager_external<_Tp>::
  457. _S_manage(_Op __which, const any* __any, _Arg* __arg)
  458. {
  459. // The contained object is *_M_storage._M_ptr
  460. auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
  461. switch (__which)
  462. {
  463. case _Op_access:
  464. __arg->_M_obj = const_cast<_Tp*>(__ptr);
  465. break;
  466. case _Op_get_type_info:
  467. #if __cpp_rtti
  468. __arg->_M_typeinfo = &typeid(_Tp);
  469. #endif
  470. break;
  471. case _Op_clone:
  472. __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
  473. __arg->_M_any->_M_manager = __any->_M_manager;
  474. break;
  475. case _Op_destroy:
  476. delete __ptr;
  477. break;
  478. case _Op_xfer:
  479. __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
  480. __arg->_M_any->_M_manager = __any->_M_manager;
  481. const_cast<any*>(__any)->_M_manager = nullptr;
  482. break;
  483. }
  484. }
  485. // Dummy specialization used by __any_caster.
  486. template<>
  487. struct any::_Manager_internal<any::_Op>
  488. {
  489. static void
  490. _S_manage(_Op, const any*, _Arg*) { }
  491. };
  492. // @} group any
  493. } // namespace fundamentals_v1
  494. } // namespace experimental
  495. _GLIBCXX_END_NAMESPACE_VERSION
  496. } // namespace std
  497. #endif // C++14
  498. #endif // _GLIBCXX_EXPERIMENTAL_ANY