1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_BIND_INTERNAL_H_
6 #define BASE_BIND_INTERNAL_H_
10 #include <type_traits>
13 #include "base/callback_internal.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/template_util.h"
18 #include "build/build_config.h"
20 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
21 #include "base/mac/scoped_block.h"
24 // See base/callback.h for user documentation.
28 // Functor -- A movable type representing something that should be called.
29 // All function pointers and Callback<> are functors even if the
30 // invocation syntax differs.
31 // RunType -- A function type (as opposed to function _pointer_ type) for
32 // a Callback<>::Run(). Usually just a convenience typedef.
33 // (Bound)Args -- A set of types that stores the arguments.
36 // ForceVoidReturn<> -- Helper class for translating function signatures to
37 // equivalent forms with a "void" return type.
38 // FunctorTraits<> -- Type traits used to determine the correct RunType and
39 // invocation manner for a Functor. This is where function
40 // signature adapters are applied.
41 // InvokeHelper<> -- Take a Functor + arguments and actully invokes it.
42 // Handle the differing syntaxes needed for WeakPtr<>
43 // support. This is separate from Invoker to avoid creating
44 // multiple version of Invoker<>.
45 // Invoker<> -- Unwraps the curried parameters and executes the Functor.
46 // BindState<> -- Stores the curried parameters, and is the main entry point
47 // into the Bind() system.
55 } // namespace Microsoft
61 struct IsWeakReceiver;
64 struct BindUnwrapTraits;
66 template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
67 struct CallbackCancellationTraits;
71 template <typename Functor, typename SFINAE = void>
75 class UnretainedWrapper {
77 explicit UnretainedWrapper(T* o) : ptr_(o) {}
78 T* get() const { return ptr_; }
85 class ConstRefWrapper {
87 explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
88 const T& get() const { return *ptr_; }
95 class RetainedRefWrapper {
97 explicit RetainedRefWrapper(T* o) : ptr_(o) {}
98 explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
99 T* get() const { return ptr_.get(); }
102 scoped_refptr<T> ptr_;
105 template <typename T>
106 struct IgnoreResultHelper {
107 explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
108 explicit operator bool() const { return !!functor_; }
113 // An alternate implementation is to avoid the destructive copy, and instead
114 // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
115 // a class that is essentially a std::unique_ptr<>.
117 // The current implementation has the benefit though of leaving ParamTraits<>
118 // fully in callback_internal.h as well as avoiding type conversions during
120 template <typename T>
123 explicit OwnedWrapper(T* o) : ptr_(o) {}
124 ~OwnedWrapper() { delete ptr_; }
125 T* get() const { return ptr_; }
126 OwnedWrapper(OwnedWrapper&& other) {
135 // PassedWrapper is a copyable adapter for a scoper that ignores const.
137 // It is needed to get around the fact that Bind() takes a const reference to
138 // all its arguments. Because Bind() takes a const reference to avoid
139 // unnecessary copies, it is incompatible with movable-but-not-copyable
140 // types; doing a destructive "move" of the type into Bind() would violate
141 // the const correctness.
143 // This conundrum cannot be solved without either C++11 rvalue references or
144 // a O(2^n) blowup of Bind() templates to handle each combination of regular
145 // types and movable-but-not-copyable types. Thus we introduce a wrapper type
146 // that is copyable to transmit the correct type information down into
147 // BindState<>. Ignoring const in this type makes sense because it is only
148 // created when we are explicitly trying to do a destructive move.
151 // 1) PassedWrapper supports any type that has a move constructor, however
152 // the type will need to be specifically whitelisted in order for it to be
153 // bound to a Callback. We guard this explicitly at the call of Passed()
154 // to make for clear errors. Things not given to Passed() will be forwarded
155 // and stored by value which will not work for general move-only types.
156 // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
157 // scoper to a Callback and allow the Callback to execute once.
158 template <typename T>
159 class PassedWrapper {
161 explicit PassedWrapper(T&& scoper)
162 : is_valid_(true), scoper_(std::move(scoper)) {}
163 PassedWrapper(PassedWrapper&& other)
164 : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
168 return std::move(scoper_);
172 mutable bool is_valid_;
176 template <typename T>
177 using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
179 template <typename T>
180 decltype(auto) Unwrap(T&& o) {
181 return Unwrapper<T>::Unwrap(std::forward<T>(o));
184 // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
185 // method. It is used internally by Bind() to select the correct
186 // InvokeHelper that will no-op itself in the event the WeakPtr<> for
187 // the target object is invalidated.
189 // The first argument should be the type of the object that will be received by
191 template <bool is_method, typename... Args>
192 struct IsWeakMethod : std::false_type {};
194 template <typename T, typename... Args>
195 struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
197 // Packs a list of types to hold them in a single type.
198 template <typename... Types>
201 // Used for DropTypeListItem implementation.
202 template <size_t n, typename List>
203 struct DropTypeListItemImpl;
205 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
206 template <size_t n, typename T, typename... List>
207 struct DropTypeListItemImpl<n, TypeList<T, List...>>
208 : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
210 template <typename T, typename... List>
211 struct DropTypeListItemImpl<0, TypeList<T, List...>> {
212 using Type = TypeList<T, List...>;
216 struct DropTypeListItemImpl<0, TypeList<>> {
217 using Type = TypeList<>;
220 // A type-level function that drops |n| list item from given TypeList.
221 template <size_t n, typename List>
222 using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
224 // Used for TakeTypeListItem implementation.
225 template <size_t n, typename List, typename... Accum>
226 struct TakeTypeListItemImpl;
228 // Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
229 template <size_t n, typename T, typename... List, typename... Accum>
230 struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
231 : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
233 template <typename T, typename... List, typename... Accum>
234 struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
235 using Type = TypeList<Accum...>;
238 template <typename... Accum>
239 struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
240 using Type = TypeList<Accum...>;
243 // A type-level function that takes first |n| list item from given TypeList.
244 // E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
245 // TypeList<A, B, C>.
246 template <size_t n, typename List>
247 using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
249 // Used for ConcatTypeLists implementation.
250 template <typename List1, typename List2>
251 struct ConcatTypeListsImpl;
253 template <typename... Types1, typename... Types2>
254 struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
255 using Type = TypeList<Types1..., Types2...>;
258 // A type-level function that concats two TypeLists.
259 template <typename List1, typename List2>
260 using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
262 // Used for MakeFunctionType implementation.
263 template <typename R, typename ArgList>
264 struct MakeFunctionTypeImpl;
266 template <typename R, typename... Args>
267 struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
268 // MSVC 2013 doesn't support Type Alias of function types.
269 // Revisit this after we update it to newer version.
270 typedef R Type(Args...);
273 // A type-level function that constructs a function type that has |R| as its
274 // return type and has TypeLists items as its arguments.
275 template <typename R, typename ArgList>
276 using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
278 // Used for ExtractArgs and ExtractReturnType.
279 template <typename Signature>
280 struct ExtractArgsImpl;
282 template <typename R, typename... Args>
283 struct ExtractArgsImpl<R(Args...)> {
284 using ReturnType = R;
285 using ArgsList = TypeList<Args...>;
288 // A type-level function that extracts function arguments into a TypeList.
289 // E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
290 template <typename Signature>
291 using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
293 // A type-level function that extracts the return type of a function.
294 // E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
295 template <typename Signature>
296 using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
298 template <typename Callable,
299 typename Signature = decltype(&Callable::operator())>
300 struct ExtractCallableRunTypeImpl;
302 template <typename Callable, typename R, typename... Args>
303 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
304 using Type = R(Args...);
307 template <typename Callable, typename R, typename... Args>
308 struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
309 using Type = R(Args...);
312 // Evaluated to RunType of the given callable type.
314 // auto f = [](int, char*) { return 0.1; };
315 // ExtractCallableRunType<decltype(f)>
317 // double(int, char*);
318 template <typename Callable>
319 using ExtractCallableRunType =
320 typename ExtractCallableRunTypeImpl<Callable>::Type;
322 // IsCallableObject<Functor> is std::true_type if |Functor| has operator().
323 // Otherwise, it's std::false_type.
325 // IsCallableObject<void(*)()>::value is false.
328 // IsCallableObject<void(Foo::*)()>::value is false.
331 // auto f = [i]() {};
332 // IsCallableObject<decltype(f)>::value is false.
333 template <typename Functor, typename SFINAE = void>
334 struct IsCallableObject : std::false_type {};
336 template <typename Callable>
337 struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
340 // HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
341 // pointer to a RefCounted type.
342 // Implementation note: This non-specialized case handles zero-arity case only.
343 // Non-zero-arity cases should be handled by the specialization below.
344 template <typename... Args>
345 struct HasRefCountedTypeAsRawPtr : std::false_type {};
347 // Implementation note: Select true_type if the first parameter is a raw pointer
348 // to a RefCounted type. Otherwise, skip the first parameter and check rest of
349 // parameters recursively.
350 template <typename T, typename... Args>
351 struct HasRefCountedTypeAsRawPtr<T, Args...>
352 : std::conditional_t<NeedsScopedRefptrButGetsRawPtr<T>::value,
354 HasRefCountedTypeAsRawPtr<Args...>> {};
358 // Set of templates that support forcing the function return type to void.
359 template <typename Sig>
360 struct ForceVoidReturn;
362 template <typename R, typename... Args>
363 struct ForceVoidReturn<R(Args...)> {
364 using RunType = void(Args...);
369 // See description at top of file.
370 template <typename Functor, typename SFINAE>
371 struct FunctorTraits;
373 // For empty callable types.
374 // This specialization is intended to allow binding captureless lambdas by
375 // base::Bind(), based on the fact that captureless lambdas are empty while
376 // capturing lambdas are not. This also allows any functors as far as it's an
380 // // Captureless lambdas are allowed.
381 // []() {return 42;};
383 // // Capturing lambdas are *not* allowed.
385 // [x]() {return x;};
387 // // Any empty class with operator() is allowed.
389 // void operator()() const {}
390 // // No non-static member variable and no virtual functions.
392 template <typename Functor>
393 struct FunctorTraits<Functor,
394 std::enable_if_t<IsCallableObject<Functor>::value &&
395 std::is_empty<Functor>::value>> {
396 using RunType = ExtractCallableRunType<Functor>;
397 static constexpr bool is_method = false;
398 static constexpr bool is_nullable = false;
400 template <typename RunFunctor, typename... RunArgs>
401 static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
403 return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
408 template <typename R, typename... Args>
409 struct FunctorTraits<R (*)(Args...)> {
410 using RunType = R(Args...);
411 static constexpr bool is_method = false;
412 static constexpr bool is_nullable = true;
414 template <typename Function, typename... RunArgs>
415 static R Invoke(Function&& function, RunArgs&&... args) {
416 return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
420 #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
423 template <typename R, typename... Args>
424 struct FunctorTraits<R(__stdcall*)(Args...)> {
425 using RunType = R(Args...);
426 static constexpr bool is_method = false;
427 static constexpr bool is_nullable = true;
429 template <typename... RunArgs>
430 static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
431 return function(std::forward<RunArgs>(args)...);
436 template <typename R, typename... Args>
437 struct FunctorTraits<R(__fastcall*)(Args...)> {
438 using RunType = R(Args...);
439 static constexpr bool is_method = false;
440 static constexpr bool is_nullable = true;
442 template <typename... RunArgs>
443 static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
444 return function(std::forward<RunArgs>(args)...);
448 #endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
450 #if defined(OS_MACOSX)
452 // Support for Objective-C blocks. There are two implementation depending
453 // on whether Automated Reference Counting (ARC) is enabled. When ARC is
454 // enabled, then the block itself can be bound as the compiler will ensure
455 // its lifetime will be correctly managed. Otherwise, require the block to
456 // be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
457 // correctly manage the block lifetime.
459 // The two implementation ensure that the One Definition Rule (ODR) is not
460 // broken (it is not possible to write a template base::RetainBlock that would
461 // work correctly both with ARC enabled and disabled).
463 #if HAS_FEATURE(objc_arc)
465 template <typename R, typename... Args>
466 struct FunctorTraits<R (^)(Args...)> {
467 using RunType = R(Args...);
468 static constexpr bool is_method = false;
469 static constexpr bool is_nullable = true;
471 template <typename BlockType, typename... RunArgs>
472 static R Invoke(BlockType&& block, RunArgs&&... args) {
473 // According to LLVM documentation (§ 6.3), "local variables of automatic
474 // storage duration do not have precise lifetime." Use objc_precise_lifetime
475 // to ensure that the Objective-C block is not deallocated until it has
476 // finished executing even if the Callback<> is destroyed during the block
478 // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
479 __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
480 return scoped_block(std::forward<RunArgs>(args)...);
484 #else // HAS_FEATURE(objc_arc)
486 template <typename R, typename... Args>
487 struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
488 using RunType = R(Args...);
489 static constexpr bool is_method = false;
490 static constexpr bool is_nullable = true;
492 template <typename BlockType, typename... RunArgs>
493 static R Invoke(BlockType&& block, RunArgs&&... args) {
494 // Copy the block to ensure that the Objective-C block is not deallocated
495 // until it has finished executing even if the Callback<> is destroyed
496 // during the block execution.
497 base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
498 return scoped_block.get()(std::forward<RunArgs>(args)...);
502 #endif // HAS_FEATURE(objc_arc)
503 #endif // defined(OS_MACOSX)
506 template <typename R, typename Receiver, typename... Args>
507 struct FunctorTraits<R (Receiver::*)(Args...)> {
508 using RunType = R(Receiver*, Args...);
509 static constexpr bool is_method = true;
510 static constexpr bool is_nullable = true;
512 template <typename Method, typename ReceiverPtr, typename... RunArgs>
513 static R Invoke(Method method,
514 ReceiverPtr&& receiver_ptr,
516 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
520 // For const methods.
521 template <typename R, typename Receiver, typename... Args>
522 struct FunctorTraits<R (Receiver::*)(Args...) const> {
523 using RunType = R(const Receiver*, Args...);
524 static constexpr bool is_method = true;
525 static constexpr bool is_nullable = true;
527 template <typename Method, typename ReceiverPtr, typename... RunArgs>
528 static R Invoke(Method method,
529 ReceiverPtr&& receiver_ptr,
531 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
535 #ifdef __cpp_noexcept_function_type
536 // noexcept makes a distinct function type in C++17.
537 // I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
538 // different in C++17.
539 template <typename R, typename... Args>
540 struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
543 template <typename R, typename Receiver, typename... Args>
544 struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
545 : FunctorTraits<R (Receiver::*)(Args...)> {};
547 template <typename R, typename Receiver, typename... Args>
548 struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
549 : FunctorTraits<R (Receiver::*)(Args...) const> {};
552 // For IgnoreResults.
553 template <typename T>
554 struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
556 typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
558 template <typename IgnoreResultType, typename... RunArgs>
559 static void Invoke(IgnoreResultType&& ignore_result_helper,
561 FunctorTraits<T>::Invoke(
562 std::forward<IgnoreResultType>(ignore_result_helper).functor_,
563 std::forward<RunArgs>(args)...);
567 // For OnceCallbacks.
568 template <typename R, typename... Args>
569 struct FunctorTraits<OnceCallback<R(Args...)>> {
570 using RunType = R(Args...);
571 static constexpr bool is_method = false;
572 static constexpr bool is_nullable = true;
574 template <typename CallbackType, typename... RunArgs>
575 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
576 DCHECK(!callback.is_null());
577 return std::forward<CallbackType>(callback).Run(
578 std::forward<RunArgs>(args)...);
582 // For RepeatingCallbacks.
583 template <typename R, typename... Args>
584 struct FunctorTraits<RepeatingCallback<R(Args...)>> {
585 using RunType = R(Args...);
586 static constexpr bool is_method = false;
587 static constexpr bool is_nullable = true;
589 template <typename CallbackType, typename... RunArgs>
590 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
591 DCHECK(!callback.is_null());
592 return std::forward<CallbackType>(callback).Run(
593 std::forward<RunArgs>(args)...);
597 template <typename Functor>
598 using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
602 // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
604 // The normal type just calls the underlying runnable.
606 // WeakCalls need special syntax that is applied to the first argument to check
607 // if they should no-op themselves.
608 template <bool is_weak_call, typename ReturnType>
611 template <typename ReturnType>
612 struct InvokeHelper<false, ReturnType> {
613 template <typename Functor, typename... RunArgs>
614 static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
615 using Traits = MakeFunctorTraits<Functor>;
616 return Traits::Invoke(std::forward<Functor>(functor),
617 std::forward<RunArgs>(args)...);
621 template <typename ReturnType>
622 struct InvokeHelper<true, ReturnType> {
623 // WeakCalls are only supported for functions with a void return type.
624 // Otherwise, the function result would be undefined if the the WeakPtr<>
626 static_assert(std::is_void<ReturnType>::value,
627 "weak_ptrs can only bind to methods without return values");
629 template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
630 static inline void MakeItSo(Functor&& functor,
631 BoundWeakPtr&& weak_ptr,
635 using Traits = MakeFunctorTraits<Functor>;
636 Traits::Invoke(std::forward<Functor>(functor),
637 std::forward<BoundWeakPtr>(weak_ptr),
638 std::forward<RunArgs>(args)...);
644 // See description at the top of the file.
645 template <typename StorageType, typename UnboundRunType>
648 template <typename StorageType, typename R, typename... UnboundArgs>
649 struct Invoker<StorageType, R(UnboundArgs...)> {
650 static R RunOnce(BindStateBase* base,
651 PassingType<UnboundArgs>... unbound_args) {
652 // Local references to make debugger stepping easier. If in a debugger,
653 // you really want to warp ahead and step through the
654 // InvokeHelper<>::MakeItSo() call below.
655 StorageType* storage = static_cast<StorageType*>(base);
656 static constexpr size_t num_bound_args =
657 std::tuple_size<decltype(storage->bound_args_)>::value;
658 return RunImpl(std::move(storage->functor_),
659 std::move(storage->bound_args_),
660 std::make_index_sequence<num_bound_args>(),
661 std::forward<UnboundArgs>(unbound_args)...);
664 static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
665 // Local references to make debugger stepping easier. If in a debugger,
666 // you really want to warp ahead and step through the
667 // InvokeHelper<>::MakeItSo() call below.
668 const StorageType* storage = static_cast<StorageType*>(base);
669 static constexpr size_t num_bound_args =
670 std::tuple_size<decltype(storage->bound_args_)>::value;
671 return RunImpl(storage->functor_, storage->bound_args_,
672 std::make_index_sequence<num_bound_args>(),
673 std::forward<UnboundArgs>(unbound_args)...);
677 template <typename Functor, typename BoundArgsTuple, size_t... indices>
678 static inline R RunImpl(Functor&& functor,
679 BoundArgsTuple&& bound,
680 std::index_sequence<indices...>,
681 UnboundArgs&&... unbound_args) {
682 static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
684 using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
685 static constexpr bool is_weak_call =
686 IsWeakMethod<is_method,
687 std::tuple_element_t<indices, DecayedArgsTuple>...>();
689 return InvokeHelper<is_weak_call, R>::MakeItSo(
690 std::forward<Functor>(functor),
691 Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
692 std::forward<UnboundArgs>(unbound_args)...);
696 // Extracts necessary type info from Functor and BoundArgs.
697 // Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
698 template <typename Functor, typename... BoundArgs>
699 struct BindTypeHelper {
700 static constexpr size_t num_bounds = sizeof...(BoundArgs);
701 using FunctorTraits = MakeFunctorTraits<Functor>;
704 // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
705 // is a template pack of `Foo*` and `int16_t`:
706 // - RunType is `double(Foo*, int, const std::string&)`,
707 // - ReturnType is `double`,
708 // - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
709 // - BoundParamsList is `TypeList<Foo*, int>`,
710 // - UnboundParamsList is `TypeList<const std::string&>`,
711 // - BoundArgsList is `TypeList<Foo*, int16_t>`,
712 // - UnboundRunType is `double(const std::string&)`.
713 using RunType = typename FunctorTraits::RunType;
714 using ReturnType = ExtractReturnType<RunType>;
716 using RunParamsList = ExtractArgs<RunType>;
717 using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
718 using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
720 using BoundArgsList = TypeList<BoundArgs...>;
722 using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
725 template <typename Functor>
726 std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
727 const Functor& functor) {
731 template <typename Functor>
732 std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
737 // Used by QueryCancellationTraits below.
738 template <typename Functor, typename BoundArgsTuple, size_t... indices>
739 bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
740 const Functor& functor,
741 const BoundArgsTuple& bound_args,
742 std::index_sequence<indices...>) {
744 case BindStateBase::IS_CANCELLED:
745 return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
746 functor, std::get<indices>(bound_args)...);
747 case BindStateBase::MAYBE_VALID:
748 return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
749 functor, std::get<indices>(bound_args)...);
754 // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
755 // true if the callback |base| represents is canceled.
756 template <typename BindStateType>
757 bool QueryCancellationTraits(const BindStateBase* base,
758 BindStateBase::CancellationQueryMode mode) {
759 const BindStateType* storage = static_cast<const BindStateType*>(base);
760 static constexpr size_t num_bound_args =
761 std::tuple_size<decltype(storage->bound_args_)>::value;
762 return QueryCancellationTraitsImpl(
763 mode, storage->functor_, storage->bound_args_,
764 std::make_index_sequence<num_bound_args>());
767 // The base case of BanUnconstructedRefCountedReceiver that checks nothing.
768 template <typename Functor, typename Receiver, typename... Unused>
770 !(MakeFunctorTraits<Functor>::is_method &&
771 std::is_pointer<std::decay_t<Receiver>>::value &&
772 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
773 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
775 template <typename Functor>
776 void BanUnconstructedRefCountedReceiver() {}
778 // Asserts that Callback is not the first owner of a ref-counted receiver.
779 template <typename Functor, typename Receiver, typename... Unused>
781 MakeFunctorTraits<Functor>::is_method &&
782 std::is_pointer<std::decay_t<Receiver>>::value &&
783 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
784 BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
787 // It's error prone to make the implicit first reference to ref-counted types.
788 // In the example below, base::BindOnce() makes the implicit first reference
789 // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
790 // enough, the newly created instance can be destroyed before |oo| makes
791 // another reference.
793 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
796 // scoped_refptr<Foo> oo = new Foo();
798 // Instead of doing like above, please consider adding a static constructor,
799 // and keep the first reference alive explicitly.
801 // scoped_refptr<Foo> Foo::Create() {
802 // auto foo = base::WrapRefCounted(new Foo());
803 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
809 // scoped_refptr<Foo> oo = Foo::Create();
810 DCHECK(receiver->HasAtLeastOneRef())
811 << "base::Bind() refuses to create the first reference to ref-counted "
812 "objects. That is typically happens around PostTask() in their "
813 "constructor, and such objects can be destroyed before `new` returns "
814 "if the task resolves fast enough.";
819 // This stores all the state passed into Bind().
820 template <typename Functor, typename... BoundArgs>
821 struct BindState final : BindStateBase {
822 using IsCancellable = std::integral_constant<
824 CallbackCancellationTraits<Functor,
825 std::tuple<BoundArgs...>>::is_cancellable>;
827 template <typename ForwardFunctor, typename... ForwardBoundArgs>
828 static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
829 ForwardFunctor&& functor,
830 ForwardBoundArgs&&... bound_args) {
831 // Ban ref counted receivers that were not yet fully constructed to avoid
832 // a common pattern of racy situation.
833 BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
835 // IsCancellable is std::false_type if
836 // CallbackCancellationTraits<>::IsCancelled returns always false.
837 // Otherwise, it's std::true_type.
838 return new BindState(IsCancellable{}, invoke_func,
839 std::forward<ForwardFunctor>(functor),
840 std::forward<ForwardBoundArgs>(bound_args)...);
844 std::tuple<BoundArgs...> bound_args_;
847 template <typename ForwardFunctor, typename... ForwardBoundArgs>
848 explicit BindState(std::true_type,
849 BindStateBase::InvokeFuncStorage invoke_func,
850 ForwardFunctor&& functor,
851 ForwardBoundArgs&&... bound_args)
852 : BindStateBase(invoke_func,
854 &QueryCancellationTraits<BindState>),
855 functor_(std::forward<ForwardFunctor>(functor)),
856 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
857 DCHECK(!IsNull(functor_));
860 template <typename ForwardFunctor, typename... ForwardBoundArgs>
861 explicit BindState(std::false_type,
862 BindStateBase::InvokeFuncStorage invoke_func,
863 ForwardFunctor&& functor,
864 ForwardBoundArgs&&... bound_args)
865 : BindStateBase(invoke_func, &Destroy),
866 functor_(std::forward<ForwardFunctor>(functor)),
867 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
868 DCHECK(!IsNull(functor_));
871 ~BindState() = default;
873 static void Destroy(const BindStateBase* self) {
874 delete static_cast<const BindState*>(self);
878 // Used to implement MakeBindStateType.
879 template <bool is_method, typename Functor, typename... BoundArgs>
880 struct MakeBindStateTypeImpl;
882 template <typename Functor, typename... BoundArgs>
883 struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
884 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
885 "A parameter is a refcounted type and needs scoped_refptr.");
886 using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
889 template <typename Functor>
890 struct MakeBindStateTypeImpl<true, Functor> {
891 using Type = BindState<std::decay_t<Functor>>;
894 template <typename Functor, typename Receiver, typename... BoundArgs>
895 struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
897 using DecayedReceiver = std::decay_t<Receiver>;
899 static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
900 "First bound argument to a method cannot be an array.");
902 !std::is_pointer<DecayedReceiver>::value ||
903 IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
904 "Receivers may not be raw pointers. If using a raw pointer here is safe"
905 " and has no lifetime concerns, use base::Unretained() and document why"
907 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
908 "A parameter is a refcounted type and needs scoped_refptr.");
911 using Type = BindState<
912 std::decay_t<Functor>,
913 std::conditional_t<std::is_pointer<DecayedReceiver>::value,
914 scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
916 std::decay_t<BoundArgs>...>;
919 template <typename Functor, typename... BoundArgs>
920 using MakeBindStateType =
921 typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
925 } // namespace internal
927 // An injection point to control |this| pointer behavior on a method invocation.
928 // If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
929 // method, base::Bind cancels the method invocation if the receiver is tested as
931 // E.g. Foo::bar() is not called:
932 // struct Foo : base::SupportsWeakPtr<Foo> {
936 // WeakPtr<Foo> oo = nullptr;
937 // base::Bind(&Foo::bar, oo).Run();
938 template <typename T>
939 struct IsWeakReceiver : std::false_type {};
941 template <typename T>
942 struct IsWeakReceiver<internal::ConstRefWrapper<T>> : IsWeakReceiver<T> {};
944 template <typename T>
945 struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
947 // An injection point to control how bound objects passed to the target
948 // function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
949 // before the target function is invoked.
951 struct BindUnwrapTraits {
952 template <typename T>
953 static T&& Unwrap(T&& o) {
954 return std::forward<T>(o);
958 template <typename T>
959 struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
960 static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
963 template <typename T>
964 struct BindUnwrapTraits<internal::ConstRefWrapper<T>> {
965 static const T& Unwrap(const internal::ConstRefWrapper<T>& o) {
970 template <typename T>
971 struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
972 static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
975 template <typename T>
976 struct BindUnwrapTraits<internal::OwnedWrapper<T>> {
977 static T* Unwrap(const internal::OwnedWrapper<T>& o) { return o.get(); }
980 template <typename T>
981 struct BindUnwrapTraits<internal::PassedWrapper<T>> {
982 static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
986 template <typename T>
987 struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
988 static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
992 // CallbackCancellationTraits allows customization of Callback's cancellation
993 // semantics. By default, callbacks are not cancellable. A specialization should
994 // set is_cancellable = true and implement an IsCancelled() that returns if the
995 // callback should be cancelled.
996 template <typename Functor, typename BoundArgsTuple, typename SFINAE>
997 struct CallbackCancellationTraits {
998 static constexpr bool is_cancellable = false;
1001 // Specialization for method bound to weak pointer receiver.
1002 template <typename Functor, typename... BoundArgs>
1003 struct CallbackCancellationTraits<
1005 std::tuple<BoundArgs...>,
1007 internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
1008 BoundArgs...>::value>> {
1009 static constexpr bool is_cancellable = true;
1011 template <typename Receiver, typename... Args>
1012 static bool IsCancelled(const Functor&,
1013 const Receiver& receiver,
1018 template <typename Receiver, typename... Args>
1019 static bool MaybeValid(const Functor&,
1020 const Receiver& receiver,
1022 return receiver.MaybeValid();
1026 // Specialization for a nested bind.
1027 template <typename Signature, typename... BoundArgs>
1028 struct CallbackCancellationTraits<OnceCallback<Signature>,
1029 std::tuple<BoundArgs...>> {
1030 static constexpr bool is_cancellable = true;
1032 template <typename Functor>
1033 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1034 return functor.IsCancelled();
1037 template <typename Functor>
1038 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1039 return functor.MaybeValid();
1043 template <typename Signature, typename... BoundArgs>
1044 struct CallbackCancellationTraits<RepeatingCallback<Signature>,
1045 std::tuple<BoundArgs...>> {
1046 static constexpr bool is_cancellable = true;
1048 template <typename Functor>
1049 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1050 return functor.IsCancelled();
1053 template <typename Functor>
1054 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1055 return functor.MaybeValid();
1059 // Returns a RunType of bound functor.
1060 // E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
1061 template <typename Functor, typename... BoundArgs>
1062 using MakeUnboundRunType =
1063 typename internal::BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
1067 #endif // BASE_BIND_INTERNAL_H_