1 // Implementation of std::function -*- C++ -*-
3 // Copyright (C) 2004-2023 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file include/bits/std_function.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{functional}
30 #ifndef _GLIBCXX_STD_FUNCTION_H
31 #define _GLIBCXX_STD_FUNCTION_H 1
33 #pragma GCC system_header
35 #if __cplusplus < 201103L
36 # include <bits/c++0x_warning.h>
39 #include <new> // placement new
40 #include <typeinfo> // typeid
41 #include <bits/invoke.h> // __invoke_r
42 #include <bits/refwrap.h> // ref wrapper, _Maybe_unary_or_binary_function
43 #include <bits/functexcept.h> // __throw_bad_function_call
45 namespace std
_GLIBCXX_VISIBILITY(default)
47 _GLIBCXX_BEGIN_NAMESPACE_VERSION
50 * @brief Exception class thrown when class template function's
51 * operator() is called with an empty target.
54 class bad_function_call
: public std::exception
57 virtual ~bad_function_call() noexcept
;
59 const char* what() const noexcept
;
63 * Trait identifying "location-invariant" types, meaning that the
64 * address of the object (or any of its members) will not escape.
65 * Trivially copyable types are location-invariant and users can
66 * specialize this trait for other types.
68 template<typename _Tp
>
69 struct __is_location_invariant
70 : is_trivially_copyable
<_Tp
>::type
73 class _Undefined_class
;
78 const void* _M_const_object
;
79 void (*_M_function_pointer
)();
80 void (_Undefined_class::*_M_member_pointer
)();
83 union [[gnu::may_alias
]] _Any_data
85 void* _M_access() noexcept
{ return &_M_pod_data
[0]; }
86 const void* _M_access() const noexcept
{ return &_M_pod_data
[0]; }
88 template<typename _Tp
>
91 { return *static_cast<_Tp
*>(_M_access()); }
93 template<typename _Tp
>
95 _M_access() const noexcept
96 { return *static_cast<const _Tp
*>(_M_access()); }
98 _Nocopy_types _M_unused
;
99 char _M_pod_data
[sizeof(_Nocopy_types
)];
102 enum _Manager_operation
110 template<typename _Signature
>
113 /// Base class of all polymorphic function object wrappers.
117 static const size_t _M_max_size
= sizeof(_Nocopy_types
);
118 static const size_t _M_max_align
= __alignof__(_Nocopy_types
);
120 template<typename _Functor
>
124 static const bool __stored_locally
=
125 (__is_location_invariant
<_Functor
>::value
126 && sizeof(_Functor
) <= _M_max_size
127 && __alignof__(_Functor
) <= _M_max_align
128 && (_M_max_align
% __alignof__(_Functor
) == 0));
130 using _Local_storage
= integral_constant
<bool, __stored_locally
>;
132 // Retrieve a pointer to the function object
134 _M_get_pointer(const _Any_data
& __source
) noexcept
136 if _GLIBCXX17_CONSTEXPR (__stored_locally
)
138 const _Functor
& __f
= __source
._M_access
<_Functor
>();
139 return const_cast<_Functor
*>(std::__addressof(__f
));
141 else // have stored a pointer
142 return __source
._M_access
<_Functor
*>();
146 // Construct a location-invariant function object that fits within
147 // an _Any_data structure.
148 template<typename _Fn
>
150 _M_create(_Any_data
& __dest
, _Fn
&& __f
, true_type
)
152 ::new (__dest
._M_access()) _Functor(std::forward
<_Fn
>(__f
));
155 // Construct a function object on the heap and store a pointer.
156 template<typename _Fn
>
158 _M_create(_Any_data
& __dest
, _Fn
&& __f
, false_type
)
160 __dest
._M_access
<_Functor
*>()
161 = new _Functor(std::forward
<_Fn
>(__f
));
164 // Destroy an object stored in the internal buffer.
166 _M_destroy(_Any_data
& __victim
, true_type
)
168 __victim
._M_access
<_Functor
>().~_Functor();
171 // Destroy an object located on the heap.
173 _M_destroy(_Any_data
& __victim
, false_type
)
175 delete __victim
._M_access
<_Functor
*>();
180 _M_manager(_Any_data
& __dest
, const _Any_data
& __source
,
181 _Manager_operation __op
)
185 case __get_type_info
:
187 __dest
._M_access
<const type_info
*>() = &typeid(_Functor
);
189 __dest
._M_access
<const type_info
*>() = nullptr;
193 case __get_functor_ptr
:
194 __dest
._M_access
<_Functor
*>() = _M_get_pointer(__source
);
197 case __clone_functor
:
198 _M_init_functor(__dest
,
199 *const_cast<const _Functor
*>(_M_get_pointer(__source
)));
202 case __destroy_functor
:
203 _M_destroy(__dest
, _Local_storage());
209 template<typename _Fn
>
211 _M_init_functor(_Any_data
& __functor
, _Fn
&& __f
)
212 noexcept(__and_
<_Local_storage
,
213 is_nothrow_constructible
<_Functor
, _Fn
>>::value
)
215 _M_create(__functor
, std::forward
<_Fn
>(__f
), _Local_storage());
218 template<typename _Signature
>
220 _M_not_empty_function(const function
<_Signature
>& __f
) noexcept
221 { return static_cast<bool>(__f
); }
223 template<typename _Tp
>
225 _M_not_empty_function(_Tp
* __fp
) noexcept
226 { return __fp
!= nullptr; }
228 template<typename _Class
, typename _Tp
>
230 _M_not_empty_function(_Tp
_Class::* __mp
) noexcept
231 { return __mp
!= nullptr; }
233 template<typename _Tp
>
235 _M_not_empty_function(const _Tp
&) noexcept
239 _Function_base() = default;
244 _M_manager(_M_functor
, _M_functor
, __destroy_functor
);
247 bool _M_empty() const { return !_M_manager
; }
250 = bool (*)(_Any_data
&, const _Any_data
&, _Manager_operation
);
252 _Any_data _M_functor
{};
253 _Manager_type _M_manager
{};
256 template<typename _Signature
, typename _Functor
>
257 class _Function_handler
;
259 template<typename _Res
, typename _Functor
, typename
... _ArgTypes
>
260 class _Function_handler
<_Res(_ArgTypes
...), _Functor
>
261 : public _Function_base::_Base_manager
<_Functor
>
263 using _Base
= _Function_base::_Base_manager
<_Functor
>;
267 _M_manager(_Any_data
& __dest
, const _Any_data
& __source
,
268 _Manager_operation __op
)
273 case __get_type_info
:
274 __dest
._M_access
<const type_info
*>() = &typeid(_Functor
);
277 case __get_functor_ptr
:
278 __dest
._M_access
<_Functor
*>() = _Base::_M_get_pointer(__source
);
282 _Base::_M_manager(__dest
, __source
, __op
);
288 _M_invoke(const _Any_data
& __functor
, _ArgTypes
&&... __args
)
290 return std::__invoke_r
<_Res
>(*_Base::_M_get_pointer(__functor
),
291 std::forward
<_ArgTypes
>(__args
)...);
294 template<typename _Fn
>
295 static constexpr bool
296 _S_nothrow_init() noexcept
298 return __and_
<typename
_Base::_Local_storage
,
299 is_nothrow_constructible
<_Functor
, _Fn
>>::value
;
303 // Specialization for invalid types
305 class _Function_handler
<void, void>
309 _M_manager(_Any_data
&, const _Any_data
&, _Manager_operation
)
313 // Avoids instantiating ill-formed specializations of _Function_handler
314 // in std::function<_Signature>::target<_Functor>().
315 // e.g. _Function_handler<Sig, void()> and _Function_handler<Sig, void>
316 // would be ill-formed.
317 template<typename _Signature
, typename _Functor
,
318 bool __valid
= is_object
<_Functor
>::value
>
319 struct _Target_handler
320 : _Function_handler
<_Signature
, typename remove_cv
<_Functor
>::type
>
323 template<typename _Signature
, typename _Functor
>
324 struct _Target_handler
<_Signature
, _Functor
, false>
325 : _Function_handler
<void, void>
329 * @brief Polymorphic function wrapper.
333 template<typename _Res
, typename
... _ArgTypes
>
334 class function
<_Res(_ArgTypes
...)>
335 : public _Maybe_unary_or_binary_function
<_Res
, _ArgTypes
...>,
336 private _Function_base
338 // Equivalent to std::decay_t except that it produces an invalid type
339 // if the decayed type is the current specialization of std::function.
340 template<typename _Func
,
341 bool _Self
= is_same
<__remove_cvref_t
<_Func
>, function
>::value
>
343 = typename __enable_if_t
<!_Self
, decay
<_Func
>>::type
;
345 template<typename _Func
,
346 typename _DFunc
= _Decay_t
<_Func
>,
347 typename _Res2
= __invoke_result
<_DFunc
&, _ArgTypes
...>>
349 : __is_invocable_impl
<_Res2
, _Res
>::type
352 template<typename _Cond
, typename _Tp
= void>
353 using _Requires
= __enable_if_t
<_Cond::value
, _Tp
>;
355 template<typename _Functor
>
357 = _Function_handler
<_Res(_ArgTypes
...), __decay_t
<_Functor
>>;
360 typedef _Res result_type
;
362 // [3.7.2.1] construct/copy/destroy
365 * @brief Default construct creates an empty function call wrapper.
366 * @post `!(bool)*this`
369 : _Function_base() { }
372 * @brief Creates an empty function call wrapper.
373 * @post @c !(bool)*this
375 function(nullptr_t
) noexcept
376 : _Function_base() { }
379 * @brief %Function copy constructor.
380 * @param __x A %function object with identical call signature.
381 * @post `bool(*this) == bool(__x)`
383 * The newly-created %function contains a copy of the target of
384 * `__x` (if it has one).
386 function(const function
& __x
)
389 if (static_cast<bool>(__x
))
391 __x
._M_manager(_M_functor
, __x
._M_functor
, __clone_functor
);
392 _M_invoker
= __x
._M_invoker
;
393 _M_manager
= __x
._M_manager
;
398 * @brief %Function move constructor.
399 * @param __x A %function object rvalue with identical call signature.
401 * The newly-created %function contains the target of `__x`
404 function(function
&& __x
) noexcept
405 : _Function_base(), _M_invoker(__x
._M_invoker
)
407 if (static_cast<bool>(__x
))
409 _M_functor
= __x
._M_functor
;
410 _M_manager
= __x
._M_manager
;
411 __x
._M_manager
= nullptr;
412 __x
._M_invoker
= nullptr;
417 * @brief Builds a %function that targets a copy of the incoming
419 * @param __f A %function object that is callable with parameters of
420 * type `ArgTypes...` and returns a value convertible to `Res`.
422 * The newly-created %function object will target a copy of
423 * `__f`. If `__f` is `reference_wrapper<F>`, then this function
424 * object will contain a reference to the function object `__f.get()`.
425 * If `__f` is a null function pointer, null pointer-to-member, or
426 * empty `std::function`, the newly-created object will be empty.
428 * If `__f` is a non-null function pointer or an object of type
429 * `reference_wrapper<F>`, this function will not throw.
431 // _GLIBCXX_RESOLVE_LIB_DEFECTS
432 // 2774. std::function construction vs assignment
433 template<typename _Functor
,
434 typename _Constraints
= _Requires
<_Callable
<_Functor
>>>
435 function(_Functor
&& __f
)
436 noexcept(_Handler
<_Functor
>::template _S_nothrow_init
<_Functor
>())
439 static_assert(is_copy_constructible
<__decay_t
<_Functor
>>::value
,
440 "std::function target must be copy-constructible");
441 static_assert(is_constructible
<__decay_t
<_Functor
>, _Functor
>::value
,
442 "std::function target must be constructible from the "
443 "constructor argument");
445 using _My_handler
= _Handler
<_Functor
>;
447 if (_My_handler::_M_not_empty_function(__f
))
449 _My_handler::_M_init_functor(_M_functor
,
450 std::forward
<_Functor
>(__f
));
451 _M_invoker
= &_My_handler::_M_invoke
;
452 _M_manager
= &_My_handler::_M_manager
;
457 * @brief Function assignment operator.
458 * @param __x A %function with identical call signature.
459 * @post `(bool)*this == (bool)x`
462 * The target of `__x` is copied to `*this`. If `__x` has no
463 * target, then `*this` will be empty.
465 * If `__x` targets a function pointer or a reference to a function
466 * object, then this operation will not throw an exception.
469 operator=(const function
& __x
)
471 function(__x
).swap(*this);
476 * @brief Function move-assignment operator.
477 * @param __x A %function rvalue with identical call signature.
480 * The target of `__x` is moved to `*this`. If `__x` has no
481 * target, then `*this` will be empty.
483 * If `__x` targets a function pointer or a reference to a function
484 * object, then this operation will not throw an exception.
487 operator=(function
&& __x
) noexcept
489 function(std::move(__x
)).swap(*this);
494 * @brief Function assignment to empty.
495 * @post `!(bool)*this`
498 * The target of `*this` is deallocated, leaving it empty.
501 operator=(nullptr_t
) noexcept
505 _M_manager(_M_functor
, _M_functor
, __destroy_functor
);
506 _M_manager
= nullptr;
507 _M_invoker
= nullptr;
513 * @brief Function assignment to a new target.
514 * @param __f A function object that is callable with parameters of
515 * type `_ArgTypes...` and returns a value convertible
520 * This function object wrapper will target a copy of `__f`. If `__f`
521 * is `reference_wrapper<F>`, then this function object will contain
522 * a reference to the function object `__f.get()`. If `__f` is a null
523 * function pointer or null pointer-to-member, this object will be
526 * If `__f` is a non-null function pointer or an object of type
527 * `reference_wrapper<F>`, this function will not throw.
529 template<typename _Functor
>
530 _Requires
<_Callable
<_Functor
>, function
&>
531 operator=(_Functor
&& __f
)
532 noexcept(_Handler
<_Functor
>::template _S_nothrow_init
<_Functor
>())
534 function(std::forward
<_Functor
>(__f
)).swap(*this);
539 template<typename _Functor
>
541 operator=(reference_wrapper
<_Functor
> __f
) noexcept
543 function(__f
).swap(*this);
547 // [3.7.2.2] function modifiers
550 * @brief Swap the targets of two %function objects.
551 * @param __x A %function with identical call signature.
553 * Swap the targets of `this` function object and `__f`.
554 * This function will not throw exceptions.
556 void swap(function
& __x
) noexcept
558 std::swap(_M_functor
, __x
._M_functor
);
559 std::swap(_M_manager
, __x
._M_manager
);
560 std::swap(_M_invoker
, __x
._M_invoker
);
563 // [3.7.2.3] function capacity
566 * @brief Determine if the %function wrapper has a target.
568 * @return `true` when this function object contains a target,
569 * or `false` when it is empty.
571 * This function will not throw exceptions.
573 explicit operator bool() const noexcept
574 { return !_M_empty(); }
576 // [3.7.2.4] function invocation
579 * @brief Invokes the function targeted by `*this`.
580 * @returns the result of the target.
581 * @throws `bad_function_call` when `!(bool)*this`
583 * The function call operator invokes the target function object
587 operator()(_ArgTypes
... __args
) const
590 __throw_bad_function_call();
591 return _M_invoker(_M_functor
, std::forward
<_ArgTypes
>(__args
)...);
595 // [3.7.2.5] function target access
597 * @brief Determine the type of the target of this function object
600 * @returns the type identifier of the target function object, or
601 * `typeid(void)` if `!(bool)*this`.
603 * This function will not throw exceptions.
606 target_type() const noexcept
610 _Any_data __typeinfo_result
;
611 _M_manager(__typeinfo_result
, _M_functor
, __get_type_info
);
612 if (auto __ti
= __typeinfo_result
._M_access
<const type_info
*>())
620 * @brief Access the stored target function object.
622 * @return Returns a pointer to the stored target function object,
623 * if `typeid(_Functor).equals(target_type())`; otherwise, a null
626 * This function does not throw exceptions.
630 template<typename _Functor
>
634 const function
* __const_this
= this;
635 const _Functor
* __func
= __const_this
->template target
<_Functor
>();
636 // If is_function_v<_Functor> is true then const_cast<_Functor*>
637 // would be ill-formed, so use *const_cast<_Functor**> instead.
638 return *const_cast<_Functor
**>(&__func
);
641 template<typename _Functor
>
643 target() const noexcept
645 if _GLIBCXX17_CONSTEXPR (is_object
<_Functor
>::value
)
647 // For C++11 and C++14 if-constexpr is not used above, so
648 // _Target_handler avoids ill-formed _Function_handler types.
649 using _Handler
= _Target_handler
<_Res(_ArgTypes
...), _Functor
>;
651 if (_M_manager
== &_Handler::_M_manager
653 || (_M_manager
&& typeid(_Functor
) == target_type())
658 _M_manager(__ptr
, _M_functor
, __get_functor_ptr
);
659 return __ptr
._M_access
<const _Functor
*>();
667 using _Invoker_type
= _Res (*)(const _Any_data
&, _ArgTypes
&&...);
668 _Invoker_type _M_invoker
= nullptr;
671 #if __cpp_deduction_guides >= 201606
673 struct __function_guide_helper
676 template<typename _Res
, typename _Tp
, bool _Nx
, typename
... _Args
>
677 struct __function_guide_helper
<
678 _Res (_Tp::*) (_Args
...) noexcept(_Nx
)
680 { using type
= _Res(_Args
...); };
682 template<typename _Res
, typename _Tp
, bool _Nx
, typename
... _Args
>
683 struct __function_guide_helper
<
684 _Res (_Tp::*) (_Args
...) & noexcept(_Nx
)
686 { using type
= _Res(_Args
...); };
688 template<typename _Res
, typename _Tp
, bool _Nx
, typename
... _Args
>
689 struct __function_guide_helper
<
690 _Res (_Tp::*) (_Args
...) const noexcept(_Nx
)
692 { using type
= _Res(_Args
...); };
694 template<typename _Res
, typename _Tp
, bool _Nx
, typename
... _Args
>
695 struct __function_guide_helper
<
696 _Res (_Tp::*) (_Args
...) const & noexcept(_Nx
)
698 { using type
= _Res(_Args
...); };
700 #if __cpp_static_call_operator >= 202207L && __cpp_concepts >= 202002L
701 template<typename _StaticCallOp
>
702 struct __function_guide_static_helper
705 template<typename _Res
, bool _Nx
, typename
... _Args
>
706 struct __function_guide_static_helper
<_Res (*) (_Args
...) noexcept(_Nx
)>
707 { using type
= _Res(_Args
...); };
709 template<typename _Fn
, typename _Op
>
710 using __function_guide_t
= typename __conditional_t
<
711 requires (_Fn
& __f
) { (void) __f
.operator(); },
712 __function_guide_static_helper
<_Op
>,
713 __function_guide_helper
<_Op
>>::type
;
715 template<typename _Fn
, typename _Op
>
716 using __function_guide_t
= typename __function_guide_helper
<_Op
>::type
;
719 template<typename _Res
, typename
... _ArgTypes
>
720 function(_Res(*)(_ArgTypes
...)) -> function
<_Res(_ArgTypes
...)>;
722 template<typename _Fn
, typename _Signature
723 = __function_guide_t
<_Fn
, decltype(&_Fn::operator())>>
724 function(_Fn
) -> function
<_Signature
>;
727 // [20.7.15.2.6] null pointer comparisons
730 * @brief Test whether a polymorphic function object wrapper is empty.
731 * @returns `true` if the wrapper has no target, `false` otherwise
733 * This function will not throw exceptions.
735 template<typename _Res
, typename
... _Args
>
737 operator==(const function
<_Res(_Args
...)>& __f
, nullptr_t
) noexcept
738 { return !static_cast<bool>(__f
); }
740 #if __cpp_impl_three_way_comparison < 201907L
742 template<typename _Res
, typename
... _Args
>
744 operator==(nullptr_t
, const function
<_Res(_Args
...)>& __f
) noexcept
745 { return !static_cast<bool>(__f
); }
748 * @brief Test whether a polymorphic function object wrapper is non-empty.
749 * @returns `false` if the wrapper has no target, `true` otherwise
751 * This function will not throw exceptions.
753 template<typename _Res
, typename
... _Args
>
755 operator!=(const function
<_Res(_Args
...)>& __f
, nullptr_t
) noexcept
756 { return static_cast<bool>(__f
); }
759 template<typename _Res
, typename
... _Args
>
761 operator!=(nullptr_t
, const function
<_Res(_Args
...)>& __f
) noexcept
762 { return static_cast<bool>(__f
); }
765 // [20.7.15.2.7] specialized algorithms
768 * @brief Swap the targets of two polymorphic function object wrappers.
770 * This function will not throw exceptions.
772 // _GLIBCXX_RESOLVE_LIB_DEFECTS
773 // 2062. Effect contradictions w/o no-throw guarantee of std::function swaps
774 template<typename _Res
, typename
... _Args
>
776 swap(function
<_Res(_Args
...)>& __x
, function
<_Res(_Args
...)>& __y
) noexcept
779 #if __cplusplus >= 201703L
780 namespace __detail::__variant
782 template<typename
> struct _Never_valueless_alt
; // see <variant>
784 // Provide the strong exception-safety guarantee when emplacing a
785 // function into a variant.
786 template<typename _Signature
>
787 struct _Never_valueless_alt
<std::function
<_Signature
>>
790 } // namespace __detail::__variant
793 _GLIBCXX_END_NAMESPACE_VERSION
797 #endif // _GLIBCXX_STD_FUNCTION_H