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.

742 lines
21KB

  1. // Implementation of std::function -*- C++ -*-
  2. // Copyright (C) 2004-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/bits/std_function.h
  21. * This is an internal header file, included by other library headers.
  22. * Do not attempt to use it directly. @headername{functional}
  23. */
  24. #ifndef _GLIBCXX_STD_FUNCTION_H
  25. #define _GLIBCXX_STD_FUNCTION_H 1
  26. #pragma GCC system_header
  27. #if __cplusplus < 201103L
  28. # include <bits/c++0x_warning.h>
  29. #else
  30. #if __cpp_rtti
  31. # include <typeinfo>
  32. #endif
  33. #include <bits/stl_function.h>
  34. #include <bits/invoke.h>
  35. #include <bits/refwrap.h>
  36. #include <bits/functexcept.h>
  37. namespace std _GLIBCXX_VISIBILITY(default)
  38. {
  39. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  40. /**
  41. * @brief Exception class thrown when class template function's
  42. * operator() is called with an empty target.
  43. * @ingroup exceptions
  44. */
  45. class bad_function_call : public std::exception
  46. {
  47. public:
  48. virtual ~bad_function_call() noexcept;
  49. const char* what() const noexcept;
  50. };
  51. /**
  52. * Trait identifying "location-invariant" types, meaning that the
  53. * address of the object (or any of its members) will not escape.
  54. * Trivially copyable types are location-invariant and users can
  55. * specialize this trait for other types.
  56. */
  57. template<typename _Tp>
  58. struct __is_location_invariant
  59. : is_trivially_copyable<_Tp>::type
  60. { };
  61. class _Undefined_class;
  62. union _Nocopy_types
  63. {
  64. void* _M_object;
  65. const void* _M_const_object;
  66. void (*_M_function_pointer)();
  67. void (_Undefined_class::*_M_member_pointer)();
  68. };
  69. union [[gnu::may_alias]] _Any_data
  70. {
  71. void* _M_access() { return &_M_pod_data[0]; }
  72. const void* _M_access() const { return &_M_pod_data[0]; }
  73. template<typename _Tp>
  74. _Tp&
  75. _M_access()
  76. { return *static_cast<_Tp*>(_M_access()); }
  77. template<typename _Tp>
  78. const _Tp&
  79. _M_access() const
  80. { return *static_cast<const _Tp*>(_M_access()); }
  81. _Nocopy_types _M_unused;
  82. char _M_pod_data[sizeof(_Nocopy_types)];
  83. };
  84. enum _Manager_operation
  85. {
  86. __get_type_info,
  87. __get_functor_ptr,
  88. __clone_functor,
  89. __destroy_functor
  90. };
  91. template<typename _Signature>
  92. class function;
  93. /// Base class of all polymorphic function object wrappers.
  94. class _Function_base
  95. {
  96. public:
  97. static const size_t _M_max_size = sizeof(_Nocopy_types);
  98. static const size_t _M_max_align = __alignof__(_Nocopy_types);
  99. template<typename _Functor>
  100. class _Base_manager
  101. {
  102. protected:
  103. static const bool __stored_locally =
  104. (__is_location_invariant<_Functor>::value
  105. && sizeof(_Functor) <= _M_max_size
  106. && __alignof__(_Functor) <= _M_max_align
  107. && (_M_max_align % __alignof__(_Functor) == 0));
  108. typedef integral_constant<bool, __stored_locally> _Local_storage;
  109. // Retrieve a pointer to the function object
  110. static _Functor*
  111. _M_get_pointer(const _Any_data& __source)
  112. {
  113. if _GLIBCXX17_CONSTEXPR (__stored_locally)
  114. {
  115. const _Functor& __f = __source._M_access<_Functor>();
  116. return const_cast<_Functor*>(std::__addressof(__f));
  117. }
  118. else // have stored a pointer
  119. return __source._M_access<_Functor*>();
  120. }
  121. // Clone a location-invariant function object that fits within
  122. // an _Any_data structure.
  123. static void
  124. _M_clone(_Any_data& __dest, const _Any_data& __source, true_type)
  125. {
  126. ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
  127. }
  128. // Clone a function object that is not location-invariant or
  129. // that cannot fit into an _Any_data structure.
  130. static void
  131. _M_clone(_Any_data& __dest, const _Any_data& __source, false_type)
  132. {
  133. __dest._M_access<_Functor*>() =
  134. new _Functor(*__source._M_access<const _Functor*>());
  135. }
  136. // Destroying a location-invariant object may still require
  137. // destruction.
  138. static void
  139. _M_destroy(_Any_data& __victim, true_type)
  140. {
  141. __victim._M_access<_Functor>().~_Functor();
  142. }
  143. // Destroying an object located on the heap.
  144. static void
  145. _M_destroy(_Any_data& __victim, false_type)
  146. {
  147. delete __victim._M_access<_Functor*>();
  148. }
  149. public:
  150. static bool
  151. _M_manager(_Any_data& __dest, const _Any_data& __source,
  152. _Manager_operation __op)
  153. {
  154. switch (__op)
  155. {
  156. #if __cpp_rtti
  157. case __get_type_info:
  158. __dest._M_access<const type_info*>() = &typeid(_Functor);
  159. break;
  160. #endif
  161. case __get_functor_ptr:
  162. __dest._M_access<_Functor*>() = _M_get_pointer(__source);
  163. break;
  164. case __clone_functor:
  165. _M_clone(__dest, __source, _Local_storage());
  166. break;
  167. case __destroy_functor:
  168. _M_destroy(__dest, _Local_storage());
  169. break;
  170. }
  171. return false;
  172. }
  173. static void
  174. _M_init_functor(_Any_data& __functor, _Functor&& __f)
  175. { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
  176. template<typename _Signature>
  177. static bool
  178. _M_not_empty_function(const function<_Signature>& __f)
  179. { return static_cast<bool>(__f); }
  180. template<typename _Tp>
  181. static bool
  182. _M_not_empty_function(_Tp* __fp)
  183. { return __fp != nullptr; }
  184. template<typename _Class, typename _Tp>
  185. static bool
  186. _M_not_empty_function(_Tp _Class::* __mp)
  187. { return __mp != nullptr; }
  188. template<typename _Tp>
  189. static bool
  190. _M_not_empty_function(const _Tp&)
  191. { return true; }
  192. private:
  193. static void
  194. _M_init_functor(_Any_data& __functor, _Functor&& __f, true_type)
  195. { ::new (__functor._M_access()) _Functor(std::move(__f)); }
  196. static void
  197. _M_init_functor(_Any_data& __functor, _Functor&& __f, false_type)
  198. { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
  199. };
  200. _Function_base() : _M_manager(nullptr) { }
  201. ~_Function_base()
  202. {
  203. if (_M_manager)
  204. _M_manager(_M_functor, _M_functor, __destroy_functor);
  205. }
  206. bool _M_empty() const { return !_M_manager; }
  207. typedef bool (*_Manager_type)(_Any_data&, const _Any_data&,
  208. _Manager_operation);
  209. _Any_data _M_functor;
  210. _Manager_type _M_manager;
  211. };
  212. template<typename _Signature, typename _Functor>
  213. class _Function_handler;
  214. template<typename _Res, typename _Functor, typename... _ArgTypes>
  215. class _Function_handler<_Res(_ArgTypes...), _Functor>
  216. : public _Function_base::_Base_manager<_Functor>
  217. {
  218. typedef _Function_base::_Base_manager<_Functor> _Base;
  219. public:
  220. static bool
  221. _M_manager(_Any_data& __dest, const _Any_data& __source,
  222. _Manager_operation __op)
  223. {
  224. switch (__op)
  225. {
  226. #if __cpp_rtti
  227. case __get_type_info:
  228. __dest._M_access<const type_info*>() = &typeid(_Functor);
  229. break;
  230. #endif
  231. case __get_functor_ptr:
  232. __dest._M_access<_Functor*>() = _Base::_M_get_pointer(__source);
  233. break;
  234. default:
  235. _Base::_M_manager(__dest, __source, __op);
  236. }
  237. return false;
  238. }
  239. static _Res
  240. _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args)
  241. {
  242. return std::__invoke_r<_Res>(*_Base::_M_get_pointer(__functor),
  243. std::forward<_ArgTypes>(__args)...);
  244. }
  245. };
  246. /**
  247. * @brief Primary class template for std::function.
  248. * @ingroup functors
  249. *
  250. * Polymorphic function wrapper.
  251. */
  252. template<typename _Res, typename... _ArgTypes>
  253. class function<_Res(_ArgTypes...)>
  254. : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,
  255. private _Function_base
  256. {
  257. template<typename _Func,
  258. typename _Res2 = __invoke_result<_Func&, _ArgTypes...>>
  259. struct _Callable
  260. : __is_invocable_impl<_Res2, _Res>::type
  261. { };
  262. // Used so the return type convertibility checks aren't done when
  263. // performing overload resolution for copy construction/assignment.
  264. template<typename _Tp>
  265. struct _Callable<function, _Tp> : false_type { };
  266. template<typename _Cond, typename _Tp>
  267. using _Requires = typename enable_if<_Cond::value, _Tp>::type;
  268. public:
  269. typedef _Res result_type;
  270. // [3.7.2.1] construct/copy/destroy
  271. /**
  272. * @brief Default construct creates an empty function call wrapper.
  273. * @post @c !(bool)*this
  274. */
  275. function() noexcept
  276. : _Function_base() { }
  277. /**
  278. * @brief Creates an empty function call wrapper.
  279. * @post @c !(bool)*this
  280. */
  281. function(nullptr_t) noexcept
  282. : _Function_base() { }
  283. /**
  284. * @brief %Function copy constructor.
  285. * @param __x A %function object with identical call signature.
  286. * @post @c bool(*this) == bool(__x)
  287. *
  288. * The newly-created %function contains a copy of the target of @a
  289. * __x (if it has one).
  290. */
  291. function(const function& __x);
  292. /**
  293. * @brief %Function move constructor.
  294. * @param __x A %function object rvalue with identical call signature.
  295. *
  296. * The newly-created %function contains the target of @a __x
  297. * (if it has one).
  298. */
  299. function(function&& __x) noexcept : _Function_base()
  300. {
  301. __x.swap(*this);
  302. }
  303. /**
  304. * @brief Builds a %function that targets a copy of the incoming
  305. * function object.
  306. * @param __f A %function object that is callable with parameters of
  307. * type @c T1, @c T2, ..., @c TN and returns a value convertible
  308. * to @c Res.
  309. *
  310. * The newly-created %function object will target a copy of
  311. * @a __f. If @a __f is @c reference_wrapper<F>, then this function
  312. * object will contain a reference to the function object @c
  313. * __f.get(). If @a __f is a NULL function pointer or NULL
  314. * pointer-to-member, the newly-created object will be empty.
  315. *
  316. * If @a __f is a non-NULL function pointer or an object of type @c
  317. * reference_wrapper<F>, this function will not throw.
  318. */
  319. template<typename _Functor,
  320. typename = _Requires<__not_<is_same<_Functor, function>>, void>,
  321. typename = _Requires<_Callable<_Functor>, void>>
  322. function(_Functor);
  323. /**
  324. * @brief %Function assignment operator.
  325. * @param __x A %function with identical call signature.
  326. * @post @c (bool)*this == (bool)x
  327. * @returns @c *this
  328. *
  329. * The target of @a __x is copied to @c *this. If @a __x has no
  330. * target, then @c *this will be empty.
  331. *
  332. * If @a __x targets a function pointer or a reference to a function
  333. * object, then this operation will not throw an %exception.
  334. */
  335. function&
  336. operator=(const function& __x)
  337. {
  338. function(__x).swap(*this);
  339. return *this;
  340. }
  341. /**
  342. * @brief %Function move-assignment operator.
  343. * @param __x A %function rvalue with identical call signature.
  344. * @returns @c *this
  345. *
  346. * The target of @a __x is moved to @c *this. If @a __x has no
  347. * target, then @c *this will be empty.
  348. *
  349. * If @a __x targets a function pointer or a reference to a function
  350. * object, then this operation will not throw an %exception.
  351. */
  352. function&
  353. operator=(function&& __x) noexcept
  354. {
  355. function(std::move(__x)).swap(*this);
  356. return *this;
  357. }
  358. /**
  359. * @brief %Function assignment to zero.
  360. * @post @c !(bool)*this
  361. * @returns @c *this
  362. *
  363. * The target of @c *this is deallocated, leaving it empty.
  364. */
  365. function&
  366. operator=(nullptr_t) noexcept
  367. {
  368. if (_M_manager)
  369. {
  370. _M_manager(_M_functor, _M_functor, __destroy_functor);
  371. _M_manager = nullptr;
  372. _M_invoker = nullptr;
  373. }
  374. return *this;
  375. }
  376. /**
  377. * @brief %Function assignment to a new target.
  378. * @param __f A %function object that is callable with parameters of
  379. * type @c T1, @c T2, ..., @c TN and returns a value convertible
  380. * to @c Res.
  381. * @return @c *this
  382. *
  383. * This %function object wrapper will target a copy of @a
  384. * __f. If @a __f is @c reference_wrapper<F>, then this function
  385. * object will contain a reference to the function object @c
  386. * __f.get(). If @a __f is a NULL function pointer or NULL
  387. * pointer-to-member, @c this object will be empty.
  388. *
  389. * If @a __f is a non-NULL function pointer or an object of type @c
  390. * reference_wrapper<F>, this function will not throw.
  391. */
  392. template<typename _Functor>
  393. _Requires<_Callable<typename decay<_Functor>::type>, function&>
  394. operator=(_Functor&& __f)
  395. {
  396. function(std::forward<_Functor>(__f)).swap(*this);
  397. return *this;
  398. }
  399. /// @overload
  400. template<typename _Functor>
  401. function&
  402. operator=(reference_wrapper<_Functor> __f) noexcept
  403. {
  404. function(__f).swap(*this);
  405. return *this;
  406. }
  407. // [3.7.2.2] function modifiers
  408. /**
  409. * @brief Swap the targets of two %function objects.
  410. * @param __x A %function with identical call signature.
  411. *
  412. * Swap the targets of @c this function object and @a __f. This
  413. * function will not throw an %exception.
  414. */
  415. void swap(function& __x) noexcept
  416. {
  417. std::swap(_M_functor, __x._M_functor);
  418. std::swap(_M_manager, __x._M_manager);
  419. std::swap(_M_invoker, __x._M_invoker);
  420. }
  421. // [3.7.2.3] function capacity
  422. /**
  423. * @brief Determine if the %function wrapper has a target.
  424. *
  425. * @return @c true when this %function object contains a target,
  426. * or @c false when it is empty.
  427. *
  428. * This function will not throw an %exception.
  429. */
  430. explicit operator bool() const noexcept
  431. { return !_M_empty(); }
  432. // [3.7.2.4] function invocation
  433. /**
  434. * @brief Invokes the function targeted by @c *this.
  435. * @returns the result of the target.
  436. * @throws bad_function_call when @c !(bool)*this
  437. *
  438. * The function call operator invokes the target function object
  439. * stored by @c this.
  440. */
  441. _Res operator()(_ArgTypes... __args) const;
  442. #if __cpp_rtti
  443. // [3.7.2.5] function target access
  444. /**
  445. * @brief Determine the type of the target of this function object
  446. * wrapper.
  447. *
  448. * @returns the type identifier of the target function object, or
  449. * @c typeid(void) if @c !(bool)*this.
  450. *
  451. * This function will not throw an %exception.
  452. */
  453. const type_info& target_type() const noexcept;
  454. /**
  455. * @brief Access the stored target function object.
  456. *
  457. * @return Returns a pointer to the stored target function object,
  458. * if @c typeid(_Functor).equals(target_type()); otherwise, a NULL
  459. * pointer.
  460. *
  461. * This function does not throw exceptions.
  462. *
  463. * @{
  464. */
  465. template<typename _Functor> _Functor* target() noexcept;
  466. template<typename _Functor> const _Functor* target() const noexcept;
  467. // @}
  468. #endif
  469. private:
  470. using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...);
  471. _Invoker_type _M_invoker;
  472. };
  473. #if __cpp_deduction_guides >= 201606
  474. template<typename>
  475. struct __function_guide_helper
  476. { };
  477. template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
  478. struct __function_guide_helper<
  479. _Res (_Tp::*) (_Args...) noexcept(_Nx)
  480. >
  481. { using type = _Res(_Args...); };
  482. template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
  483. struct __function_guide_helper<
  484. _Res (_Tp::*) (_Args...) & noexcept(_Nx)
  485. >
  486. { using type = _Res(_Args...); };
  487. template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
  488. struct __function_guide_helper<
  489. _Res (_Tp::*) (_Args...) const noexcept(_Nx)
  490. >
  491. { using type = _Res(_Args...); };
  492. template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
  493. struct __function_guide_helper<
  494. _Res (_Tp::*) (_Args...) const & noexcept(_Nx)
  495. >
  496. { using type = _Res(_Args...); };
  497. template<typename _Res, typename... _ArgTypes>
  498. function(_Res(*)(_ArgTypes...)) -> function<_Res(_ArgTypes...)>;
  499. template<typename _Functor, typename _Signature = typename
  500. __function_guide_helper<decltype(&_Functor::operator())>::type>
  501. function(_Functor) -> function<_Signature>;
  502. #endif
  503. // Out-of-line member definitions.
  504. template<typename _Res, typename... _ArgTypes>
  505. function<_Res(_ArgTypes...)>::
  506. function(const function& __x)
  507. : _Function_base()
  508. {
  509. if (static_cast<bool>(__x))
  510. {
  511. __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
  512. _M_invoker = __x._M_invoker;
  513. _M_manager = __x._M_manager;
  514. }
  515. }
  516. template<typename _Res, typename... _ArgTypes>
  517. template<typename _Functor, typename, typename>
  518. function<_Res(_ArgTypes...)>::
  519. function(_Functor __f)
  520. : _Function_base()
  521. {
  522. typedef _Function_handler<_Res(_ArgTypes...), _Functor> _My_handler;
  523. if (_My_handler::_M_not_empty_function(__f))
  524. {
  525. _My_handler::_M_init_functor(_M_functor, std::move(__f));
  526. _M_invoker = &_My_handler::_M_invoke;
  527. _M_manager = &_My_handler::_M_manager;
  528. }
  529. }
  530. template<typename _Res, typename... _ArgTypes>
  531. _Res
  532. function<_Res(_ArgTypes...)>::
  533. operator()(_ArgTypes... __args) const
  534. {
  535. if (_M_empty())
  536. __throw_bad_function_call();
  537. return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...);
  538. }
  539. #if __cpp_rtti
  540. template<typename _Res, typename... _ArgTypes>
  541. const type_info&
  542. function<_Res(_ArgTypes...)>::
  543. target_type() const noexcept
  544. {
  545. if (_M_manager)
  546. {
  547. _Any_data __typeinfo_result;
  548. _M_manager(__typeinfo_result, _M_functor, __get_type_info);
  549. return *__typeinfo_result._M_access<const type_info*>();
  550. }
  551. else
  552. return typeid(void);
  553. }
  554. template<typename _Res, typename... _ArgTypes>
  555. template<typename _Functor>
  556. _Functor*
  557. function<_Res(_ArgTypes...)>::
  558. target() noexcept
  559. {
  560. const function* __const_this = this;
  561. const _Functor* __func = __const_this->template target<_Functor>();
  562. return const_cast<_Functor*>(__func);
  563. }
  564. template<typename _Res, typename... _ArgTypes>
  565. template<typename _Functor>
  566. const _Functor*
  567. function<_Res(_ArgTypes...)>::
  568. target() const noexcept
  569. {
  570. if (typeid(_Functor) == target_type() && _M_manager)
  571. {
  572. _Any_data __ptr;
  573. _M_manager(__ptr, _M_functor, __get_functor_ptr);
  574. return __ptr._M_access<const _Functor*>();
  575. }
  576. else
  577. return nullptr;
  578. }
  579. #endif
  580. // [20.7.15.2.6] null pointer comparisons
  581. /**
  582. * @brief Compares a polymorphic function object wrapper against 0
  583. * (the NULL pointer).
  584. * @returns @c true if the wrapper has no target, @c false otherwise
  585. *
  586. * This function will not throw an %exception.
  587. */
  588. template<typename _Res, typename... _Args>
  589. inline bool
  590. operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
  591. { return !static_cast<bool>(__f); }
  592. #if __cpp_impl_three_way_comparison < 201907L
  593. /// @overload
  594. template<typename _Res, typename... _Args>
  595. inline bool
  596. operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
  597. { return !static_cast<bool>(__f); }
  598. /**
  599. * @brief Compares a polymorphic function object wrapper against 0
  600. * (the NULL pointer).
  601. * @returns @c false if the wrapper has no target, @c true otherwise
  602. *
  603. * This function will not throw an %exception.
  604. */
  605. template<typename _Res, typename... _Args>
  606. inline bool
  607. operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
  608. { return static_cast<bool>(__f); }
  609. /// @overload
  610. template<typename _Res, typename... _Args>
  611. inline bool
  612. operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
  613. { return static_cast<bool>(__f); }
  614. #endif
  615. // [20.7.15.2.7] specialized algorithms
  616. /**
  617. * @brief Swap the targets of two polymorphic function object wrappers.
  618. *
  619. * This function will not throw an %exception.
  620. */
  621. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  622. // 2062. Effect contradictions w/o no-throw guarantee of std::function swaps
  623. template<typename _Res, typename... _Args>
  624. inline void
  625. swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y) noexcept
  626. { __x.swap(__y); }
  627. #if __cplusplus >= 201703L
  628. namespace __detail::__variant
  629. {
  630. template<typename> struct _Never_valueless_alt; // see <variant>
  631. // Provide the strong exception-safety guarantee when emplacing a
  632. // function into a variant.
  633. template<typename _Signature>
  634. struct _Never_valueless_alt<std::function<_Signature>>
  635. : std::true_type
  636. { };
  637. } // namespace __detail::__variant
  638. #endif // C++17
  639. _GLIBCXX_END_NAMESPACE_VERSION
  640. } // namespace std
  641. #endif // C++11
  642. #endif // _GLIBCXX_STD_FUNCTION_H