blob: bed151a8dce56c4aecb03c6c24e6d9238f5f4a4c [file] [log] [blame]
[email protected]b38d3572011-02-15 01:27:381// 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.
4
5#ifndef BASE_BIND_INTERNAL_H_
6#define BASE_BIND_INTERNAL_H_
[email protected]b38d3572011-02-15 01:27:387
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
9
jdoerriec79c2fa22019-02-26 12:35:0310#include <functional>
jdoerrie68f2d51b2019-02-28 17:32:4411#include <memory>
jdoerrie5c4dc4e2019-02-01 18:02:3312#include <tuple>
vmpstrc52317f2015-11-18 08:43:2613#include <type_traits>
Jeremy Roman84956fa2017-08-16 15:55:2014#include <utility>
vmpstrc52317f2015-11-18 08:43:2615
Sebastien Marchand6d0558fd2019-01-25 16:49:3716#include "base/bind.h"
[email protected]59eff912011-02-18 23:29:3117#include "base/callback_internal.h"
Sylvain Defresneec3270c2018-05-31 17:19:1518#include "base/compiler_specific.h"
[email protected]8217d4542011-10-01 06:31:4119#include "base/memory/raw_scoped_refptr_mismatch_checker.h"
[email protected]93540582011-05-16 22:35:1420#include "base/memory/weak_ptr.h"
[email protected]b38d3572011-02-15 01:27:3821#include "base/template_util.h"
[email protected]054ac7542011-02-27 01:25:5922#include "build/build_config.h"
23
Sylvain Defresneec3270c2018-05-31 17:19:1524#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
25#include "base/mac/scoped_block.h"
26#endif
27
[email protected]24292642012-07-12 20:06:4028// See base/callback.h for user documentation.
29//
30//
[email protected]7296f2762011-11-21 19:23:4431// CONCEPTS:
tzik99de02b2016-07-01 05:54:1232// Functor -- A movable type representing something that should be called.
33// All function pointers and Callback<> are functors even if the
34// invocation syntax differs.
[email protected]7296f2762011-11-21 19:23:4435// RunType -- A function type (as opposed to function _pointer_ type) for
tzik99de02b2016-07-01 05:54:1236// a Callback<>::Run(). Usually just a convenience typedef.
tzikce3ecf82015-12-15 06:41:4937// (Bound)Args -- A set of types that stores the arguments.
[email protected]b38d3572011-02-15 01:27:3838//
[email protected]7296f2762011-11-21 19:23:4439// Types:
[email protected]7296f2762011-11-21 19:23:4440// ForceVoidReturn<> -- Helper class for translating function signatures to
41// equivalent forms with a "void" return type.
tzik99de02b2016-07-01 05:54:1242// FunctorTraits<> -- Type traits used to determine the correct RunType and
43// invocation manner for a Functor. This is where function
[email protected]7296f2762011-11-21 19:23:4444// signature adapters are applied.
tzik99de02b2016-07-01 05:54:1245// InvokeHelper<> -- Take a Functor + arguments and actully invokes it.
tzik8ce65702015-02-05 19:11:2646// Handle the differing syntaxes needed for WeakPtr<>
tzik99de02b2016-07-01 05:54:1247// support. This is separate from Invoker to avoid creating
48// multiple version of Invoker<>.
49// Invoker<> -- Unwraps the curried parameters and executes the Functor.
[email protected]7296f2762011-11-21 19:23:4450// BindState<> -- Stores the curried parameters, and is the main entry point
tzik99de02b2016-07-01 05:54:1251// into the Bind() system.
[email protected]4346ef912011-02-19 00:52:1552
tzikc44f8102018-07-24 09:49:1953#if defined(OS_WIN)
54namespace Microsoft {
55namespace WRL {
56template <typename>
57class ComPtr;
58} // namespace WRL
59} // namespace Microsoft
60#endif
61
Peter Kastinga85265e32018-02-15 08:30:2362namespace base {
63
64template <typename T>
65struct IsWeakReceiver;
66
67template <typename>
68struct BindUnwrapTraits;
69
70template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
71struct CallbackCancellationTraits;
72
73namespace internal {
74
75template <typename Functor, typename SFINAE = void>
76struct FunctorTraits;
77
78template <typename T>
79class UnretainedWrapper {
80 public:
81 explicit UnretainedWrapper(T* o) : ptr_(o) {}
82 T* get() const { return ptr_; }
83
84 private:
85 T* ptr_;
86};
87
88template <typename T>
Peter Kastinga85265e32018-02-15 08:30:2389class RetainedRefWrapper {
90 public:
91 explicit RetainedRefWrapper(T* o) : ptr_(o) {}
92 explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
93 T* get() const { return ptr_.get(); }
94
95 private:
96 scoped_refptr<T> ptr_;
97};
98
99template <typename T>
100struct IgnoreResultHelper {
101 explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
102 explicit operator bool() const { return !!functor_; }
103
104 T functor_;
105};
106
Marijn Kruisselbrinkc1e775f2019-12-19 01:24:22107template <typename T, typename Deleter = std::default_delete<T>>
Peter Kastinga85265e32018-02-15 08:30:23108class OwnedWrapper {
109 public:
110 explicit OwnedWrapper(T* o) : ptr_(o) {}
Marijn Kruisselbrinkc1e775f2019-12-19 01:24:22111 explicit OwnedWrapper(std::unique_ptr<T, Deleter>&& ptr)
112 : ptr_(std::move(ptr)) {}
jdoerrie68f2d51b2019-02-28 17:32:44113 T* get() const { return ptr_.get(); }
Peter Kastinga85265e32018-02-15 08:30:23114
115 private:
Marijn Kruisselbrinkc1e775f2019-12-19 01:24:22116 std::unique_ptr<T, Deleter> ptr_;
Peter Kastinga85265e32018-02-15 08:30:23117};
118
119// PassedWrapper is a copyable adapter for a scoper that ignores const.
120//
121// It is needed to get around the fact that Bind() takes a const reference to
122// all its arguments. Because Bind() takes a const reference to avoid
123// unnecessary copies, it is incompatible with movable-but-not-copyable
124// types; doing a destructive "move" of the type into Bind() would violate
125// the const correctness.
126//
127// This conundrum cannot be solved without either C++11 rvalue references or
128// a O(2^n) blowup of Bind() templates to handle each combination of regular
129// types and movable-but-not-copyable types. Thus we introduce a wrapper type
130// that is copyable to transmit the correct type information down into
131// BindState<>. Ignoring const in this type makes sense because it is only
132// created when we are explicitly trying to do a destructive move.
133//
134// Two notes:
135// 1) PassedWrapper supports any type that has a move constructor, however
136// the type will need to be specifically whitelisted in order for it to be
137// bound to a Callback. We guard this explicitly at the call of Passed()
138// to make for clear errors. Things not given to Passed() will be forwarded
139// and stored by value which will not work for general move-only types.
140// 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
141// scoper to a Callback and allow the Callback to execute once.
142template <typename T>
143class PassedWrapper {
144 public:
145 explicit PassedWrapper(T&& scoper)
146 : is_valid_(true), scoper_(std::move(scoper)) {}
147 PassedWrapper(PassedWrapper&& other)
148 : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
149 T Take() const {
150 CHECK(is_valid_);
151 is_valid_ = false;
152 return std::move(scoper_);
153 }
154
155 private:
156 mutable bool is_valid_;
157 mutable T scoper_;
158};
159
160template <typename T>
161using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
162
163template <typename T>
Peter Kastingc2f8749bf2018-03-31 03:32:37164decltype(auto) Unwrap(T&& o) {
Peter Kastinga85265e32018-02-15 08:30:23165 return Unwrapper<T>::Unwrap(std::forward<T>(o));
166}
167
168// IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
169// method. It is used internally by Bind() to select the correct
170// InvokeHelper that will no-op itself in the event the WeakPtr<> for
171// the target object is invalidated.
172//
173// The first argument should be the type of the object that will be received by
174// the method.
175template <bool is_method, typename... Args>
176struct IsWeakMethod : std::false_type {};
177
178template <typename T, typename... Args>
179struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
180
181// Packs a list of types to hold them in a single type.
182template <typename... Types>
183struct TypeList {};
184
185// Used for DropTypeListItem implementation.
186template <size_t n, typename List>
187struct DropTypeListItemImpl;
188
189// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
190template <size_t n, typename T, typename... List>
191struct DropTypeListItemImpl<n, TypeList<T, List...>>
192 : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
193
194template <typename T, typename... List>
195struct DropTypeListItemImpl<0, TypeList<T, List...>> {
196 using Type = TypeList<T, List...>;
197};
198
199template <>
200struct DropTypeListItemImpl<0, TypeList<>> {
201 using Type = TypeList<>;
202};
203
204// A type-level function that drops |n| list item from given TypeList.
205template <size_t n, typename List>
206using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
207
208// Used for TakeTypeListItem implementation.
209template <size_t n, typename List, typename... Accum>
210struct TakeTypeListItemImpl;
211
212// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
213template <size_t n, typename T, typename... List, typename... Accum>
214struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
215 : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
216
217template <typename T, typename... List, typename... Accum>
218struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
219 using Type = TypeList<Accum...>;
220};
221
222template <typename... Accum>
223struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
224 using Type = TypeList<Accum...>;
225};
226
227// A type-level function that takes first |n| list item from given TypeList.
228// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
229// TypeList<A, B, C>.
230template <size_t n, typename List>
231using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
232
233// Used for ConcatTypeLists implementation.
234template <typename List1, typename List2>
235struct ConcatTypeListsImpl;
236
237template <typename... Types1, typename... Types2>
238struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
239 using Type = TypeList<Types1..., Types2...>;
240};
241
242// A type-level function that concats two TypeLists.
243template <typename List1, typename List2>
244using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
245
246// Used for MakeFunctionType implementation.
247template <typename R, typename ArgList>
248struct MakeFunctionTypeImpl;
249
250template <typename R, typename... Args>
251struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
252 // MSVC 2013 doesn't support Type Alias of function types.
253 // Revisit this after we update it to newer version.
254 typedef R Type(Args...);
255};
256
257// A type-level function that constructs a function type that has |R| as its
258// return type and has TypeLists items as its arguments.
259template <typename R, typename ArgList>
260using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
261
262// Used for ExtractArgs and ExtractReturnType.
263template <typename Signature>
264struct ExtractArgsImpl;
265
266template <typename R, typename... Args>
267struct ExtractArgsImpl<R(Args...)> {
268 using ReturnType = R;
269 using ArgsList = TypeList<Args...>;
270};
271
272// A type-level function that extracts function arguments into a TypeList.
273// E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
274template <typename Signature>
275using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
276
277// A type-level function that extracts the return type of a function.
278// E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
279template <typename Signature>
280using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
281
tzikc1db72652016-07-08 09:42:38282template <typename Callable,
283 typename Signature = decltype(&Callable::operator())>
284struct ExtractCallableRunTypeImpl;
285
286template <typename Callable, typename R, typename... Args>
tzikf98654b2017-12-02 03:28:58287struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
288 using Type = R(Args...);
289};
290
291template <typename Callable, typename R, typename... Args>
292struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
tzikc1db72652016-07-08 09:42:38293 using Type = R(Args...);
294};
295
296// Evaluated to RunType of the given callable type.
297// Example:
298// auto f = [](int, char*) { return 0.1; };
299// ExtractCallableRunType<decltype(f)>
300// is evaluated to
301// double(int, char*);
302template <typename Callable>
303using ExtractCallableRunType =
304 typename ExtractCallableRunTypeImpl<Callable>::Type;
305
tzikf98654b2017-12-02 03:28:58306// IsCallableObject<Functor> is std::true_type if |Functor| has operator().
307// Otherwise, it's std::false_type.
tzikc1db72652016-07-08 09:42:38308// Example:
tzikf98654b2017-12-02 03:28:58309// IsCallableObject<void(*)()>::value is false.
tzikc1db72652016-07-08 09:42:38310//
311// struct Foo {};
tzikf98654b2017-12-02 03:28:58312// IsCallableObject<void(Foo::*)()>::value is false.
tzikc1db72652016-07-08 09:42:38313//
314// int i = 0;
tzikf98654b2017-12-02 03:28:58315// auto f = [i]() {};
316// IsCallableObject<decltype(f)>::value is false.
tzikc1db72652016-07-08 09:42:38317template <typename Functor, typename SFINAE = void>
tzikf98654b2017-12-02 03:28:58318struct IsCallableObject : std::false_type {};
tzikc1db72652016-07-08 09:42:38319
320template <typename Callable>
tzikf98654b2017-12-02 03:28:58321struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
322 : std::true_type {};
tzikc1db72652016-07-08 09:42:38323
tzik401dd3672014-11-26 07:54:58324// HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
325// pointer to a RefCounted type.
326// Implementation note: This non-specialized case handles zero-arity case only.
327// Non-zero-arity cases should be handled by the specialization below.
328template <typename... Args>
tzik403cb6c2016-03-10 07:17:25329struct HasRefCountedTypeAsRawPtr : std::false_type {};
tzik401dd3672014-11-26 07:54:58330
331// Implementation note: Select true_type if the first parameter is a raw pointer
332// to a RefCounted type. Otherwise, skip the first parameter and check rest of
333// parameters recursively.
334template <typename T, typename... Args>
335struct HasRefCountedTypeAsRawPtr<T, Args...>
Jeremy Roman35a317432017-08-16 22:20:53336 : std::conditional_t<NeedsScopedRefptrButGetsRawPtr<T>::value,
337 std::true_type,
338 HasRefCountedTypeAsRawPtr<Args...>> {};
tzik401dd3672014-11-26 07:54:58339
[email protected]7296f2762011-11-21 19:23:44340// ForceVoidReturn<>
341//
342// Set of templates that support forcing the function return type to void.
343template <typename Sig>
344struct ForceVoidReturn;
345
tzikc82149922014-11-20 10:09:45346template <typename R, typename... Args>
347struct ForceVoidReturn<R(Args...)> {
tzik99de02b2016-07-01 05:54:12348 using RunType = void(Args...);
[email protected]fccef1552011-11-28 22:13:54349};
350
[email protected]7296f2762011-11-21 19:23:44351// FunctorTraits<>
352//
353// See description at top of file.
tzik6c92eab2016-11-25 15:56:36354template <typename Functor, typename SFINAE>
tzik99de02b2016-07-01 05:54:12355struct FunctorTraits;
356
tzikf98654b2017-12-02 03:28:58357// For empty callable types.
kylechar2255ccc2019-09-11 21:47:23358// This specialization is intended to allow binding captureless lambdas, based
359// on the fact that captureless lambdas are empty while capturing lambdas are
360// not. This also allows any functors as far as it's an empty class.
tzikf98654b2017-12-02 03:28:58361// Example:
362//
363// // Captureless lambdas are allowed.
364// []() {return 42;};
365//
366// // Capturing lambdas are *not* allowed.
367// int x;
368// [x]() {return x;};
369//
370// // Any empty class with operator() is allowed.
371// struct Foo {
372// void operator()() const {}
373// // No non-static member variable and no virtual functions.
374// };
tzikc1db72652016-07-08 09:42:38375template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53376struct FunctorTraits<Functor,
tzikf98654b2017-12-02 03:28:58377 std::enable_if_t<IsCallableObject<Functor>::value &&
378 std::is_empty<Functor>::value>> {
tzikc1db72652016-07-08 09:42:38379 using RunType = ExtractCallableRunType<Functor>;
380 static constexpr bool is_method = false;
381 static constexpr bool is_nullable = false;
382
tzikf98654b2017-12-02 03:28:58383 template <typename RunFunctor, typename... RunArgs>
384 static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
385 RunArgs&&... args) {
386 return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
tzikc1db72652016-07-08 09:42:38387 }
388};
389
tzik99de02b2016-07-01 05:54:12390// For functions.
391template <typename R, typename... Args>
392struct FunctorTraits<R (*)(Args...)> {
393 using RunType = R(Args...);
394 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38395 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12396
tzikd58a89232018-04-26 04:29:53397 template <typename Function, typename... RunArgs>
398 static R Invoke(Function&& function, RunArgs&&... args) {
399 return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12400 }
[email protected]7296f2762011-11-21 19:23:44401};
402
Gaurav Dholf6e3f592018-10-29 17:22:41403#if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
tzik99de02b2016-07-01 05:54:12404
405// For functions.
406template <typename R, typename... Args>
407struct FunctorTraits<R(__stdcall*)(Args...)> {
408 using RunType = R(Args...);
409 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38410 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12411
412 template <typename... RunArgs>
413 static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
414 return function(std::forward<RunArgs>(args)...);
415 }
416};
417
418// For functions.
419template <typename R, typename... Args>
420struct FunctorTraits<R(__fastcall*)(Args...)> {
421 using RunType = R(Args...);
422 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38423 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12424
425 template <typename... RunArgs>
426 static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
427 return function(std::forward<RunArgs>(args)...);
428 }
429};
430
Gaurav Dholf6e3f592018-10-29 17:22:41431#endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
tzik99de02b2016-07-01 05:54:12432
Sylvain Defresneec3270c2018-05-31 17:19:15433#if defined(OS_MACOSX)
434
435// Support for Objective-C blocks. There are two implementation depending
436// on whether Automated Reference Counting (ARC) is enabled. When ARC is
437// enabled, then the block itself can be bound as the compiler will ensure
438// its lifetime will be correctly managed. Otherwise, require the block to
439// be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
440// correctly manage the block lifetime.
441//
442// The two implementation ensure that the One Definition Rule (ODR) is not
443// broken (it is not possible to write a template base::RetainBlock that would
444// work correctly both with ARC enabled and disabled).
445
446#if HAS_FEATURE(objc_arc)
447
448template <typename R, typename... Args>
449struct FunctorTraits<R (^)(Args...)> {
450 using RunType = R(Args...);
451 static constexpr bool is_method = false;
452 static constexpr bool is_nullable = true;
453
454 template <typename BlockType, typename... RunArgs>
455 static R Invoke(BlockType&& block, RunArgs&&... args) {
456 // According to LLVM documentation (§ 6.3), "local variables of automatic
457 // storage duration do not have precise lifetime." Use objc_precise_lifetime
458 // to ensure that the Objective-C block is not deallocated until it has
459 // finished executing even if the Callback<> is destroyed during the block
460 // execution.
461 // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
462 __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
463 return scoped_block(std::forward<RunArgs>(args)...);
464 }
465};
466
467#else // HAS_FEATURE(objc_arc)
468
469template <typename R, typename... Args>
470struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
471 using RunType = R(Args...);
472 static constexpr bool is_method = false;
473 static constexpr bool is_nullable = true;
474
475 template <typename BlockType, typename... RunArgs>
476 static R Invoke(BlockType&& block, RunArgs&&... args) {
477 // Copy the block to ensure that the Objective-C block is not deallocated
478 // until it has finished executing even if the Callback<> is destroyed
479 // during the block execution.
480 base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
481 return scoped_block.get()(std::forward<RunArgs>(args)...);
482 }
483};
484
485#endif // HAS_FEATURE(objc_arc)
486#endif // defined(OS_MACOSX)
487
tzik99de02b2016-07-01 05:54:12488// For methods.
489template <typename R, typename Receiver, typename... Args>
490struct FunctorTraits<R (Receiver::*)(Args...)> {
491 using RunType = R(Receiver*, Args...);
492 static constexpr bool is_method = true;
tzikc1db72652016-07-08 09:42:38493 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12494
tzikd58a89232018-04-26 04:29:53495 template <typename Method, typename ReceiverPtr, typename... RunArgs>
496 static R Invoke(Method method,
tzik99de02b2016-07-01 05:54:12497 ReceiverPtr&& receiver_ptr,
498 RunArgs&&... args) {
tzik75851f42017-06-14 06:57:01499 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12500 }
501};
502
503// For const methods.
504template <typename R, typename Receiver, typename... Args>
505struct FunctorTraits<R (Receiver::*)(Args...) const> {
506 using RunType = R(const Receiver*, Args...);
507 static constexpr bool is_method = true;
tzikc1db72652016-07-08 09:42:38508 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12509
tzikd58a89232018-04-26 04:29:53510 template <typename Method, typename ReceiverPtr, typename... RunArgs>
511 static R Invoke(Method method,
tzik99de02b2016-07-01 05:54:12512 ReceiverPtr&& receiver_ptr,
513 RunArgs&&... args) {
tzik75851f42017-06-14 06:57:01514 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12515 }
516};
517
tzikd58a89232018-04-26 04:29:53518#ifdef __cpp_noexcept_function_type
519// noexcept makes a distinct function type in C++17.
520// I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
521// different in C++17.
522template <typename R, typename... Args>
523struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
524};
525
526template <typename R, typename Receiver, typename... Args>
527struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
528 : FunctorTraits<R (Receiver::*)(Args...)> {};
529
530template <typename R, typename Receiver, typename... Args>
531struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
532 : FunctorTraits<R (Receiver::*)(Args...) const> {};
533#endif
534
tzik99de02b2016-07-01 05:54:12535// For IgnoreResults.
[email protected]7296f2762011-11-21 19:23:44536template <typename T>
tzik99de02b2016-07-01 05:54:12537struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
tzik3bc7779b2015-12-19 09:18:46538 using RunType =
tzik99de02b2016-07-01 05:54:12539 typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
540
541 template <typename IgnoreResultType, typename... RunArgs>
542 static void Invoke(IgnoreResultType&& ignore_result_helper,
543 RunArgs&&... args) {
tzikff54a5b152016-08-31 11:50:41544 FunctorTraits<T>::Invoke(
545 std::forward<IgnoreResultType>(ignore_result_helper).functor_,
546 std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12547 }
[email protected]7296f2762011-11-21 19:23:44548};
549
tzikd4bb5b7d2017-08-28 19:08:52550// For OnceCallbacks.
551template <typename R, typename... Args>
552struct FunctorTraits<OnceCallback<R(Args...)>> {
553 using RunType = R(Args...);
554 static constexpr bool is_method = false;
555 static constexpr bool is_nullable = true;
556
557 template <typename CallbackType, typename... RunArgs>
558 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
559 DCHECK(!callback.is_null());
560 return std::forward<CallbackType>(callback).Run(
561 std::forward<RunArgs>(args)...);
562 }
563};
564
565// For RepeatingCallbacks.
566template <typename R, typename... Args>
567struct FunctorTraits<RepeatingCallback<R(Args...)>> {
tzik99de02b2016-07-01 05:54:12568 using RunType = R(Args...);
569 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38570 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12571
572 template <typename CallbackType, typename... RunArgs>
573 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
574 DCHECK(!callback.is_null());
575 return std::forward<CallbackType>(callback).Run(
576 std::forward<RunArgs>(args)...);
577 }
[email protected]7296f2762011-11-21 19:23:44578};
579
tzikae4202e2017-07-31 10:41:54580template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53581using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
tzikae4202e2017-07-31 10:41:54582
[email protected]7296f2762011-11-21 19:23:44583// InvokeHelper<>
584//
tzik99de02b2016-07-01 05:54:12585// There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
[email protected]7296f2762011-11-21 19:23:44586//
587// The normal type just calls the underlying runnable.
588//
tzik99de02b2016-07-01 05:54:12589// WeakCalls need special syntax that is applied to the first argument to check
590// if they should no-op themselves.
tzikee248722016-06-01 08:22:51591template <bool is_weak_call, typename ReturnType>
[email protected]7296f2762011-11-21 19:23:44592struct InvokeHelper;
593
tzikee248722016-06-01 08:22:51594template <typename ReturnType>
595struct InvokeHelper<false, ReturnType> {
tzik99de02b2016-07-01 05:54:12596 template <typename Functor, typename... RunArgs>
597 static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
tzikae4202e2017-07-31 10:41:54598 using Traits = MakeFunctorTraits<Functor>;
tzik99de02b2016-07-01 05:54:12599 return Traits::Invoke(std::forward<Functor>(functor),
600 std::forward<RunArgs>(args)...);
[email protected]7296f2762011-11-21 19:23:44601 }
602};
603
tzikee248722016-06-01 08:22:51604template <typename ReturnType>
605struct InvokeHelper<true, ReturnType> {
[email protected]7296f2762011-11-21 19:23:44606 // WeakCalls are only supported for functions with a void return type.
607 // Otherwise, the function result would be undefined if the the WeakPtr<>
608 // is invalidated.
tzik403cb6c2016-03-10 07:17:25609 static_assert(std::is_void<ReturnType>::value,
avi4ec0dff2015-11-24 14:26:24610 "weak_ptrs can only bind to methods without return values");
[email protected]c18b1052011-03-24 02:02:17611
tzik99de02b2016-07-01 05:54:12612 template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
613 static inline void MakeItSo(Functor&& functor,
tzik33871d82016-07-14 12:12:06614 BoundWeakPtr&& weak_ptr,
tzik99de02b2016-07-01 05:54:12615 RunArgs&&... args) {
616 if (!weak_ptr)
617 return;
tzikae4202e2017-07-31 10:41:54618 using Traits = MakeFunctorTraits<Functor>;
tzik99de02b2016-07-01 05:54:12619 Traits::Invoke(std::forward<Functor>(functor),
620 std::forward<BoundWeakPtr>(weak_ptr),
621 std::forward<RunArgs>(args)...);
622 }
623};
[email protected]b38d3572011-02-15 01:27:38624
[email protected]7296f2762011-11-21 19:23:44625// Invoker<>
626//
627// See description at the top of the file.
tzikcaf1d84b2016-06-28 12:22:21628template <typename StorageType, typename UnboundRunType>
[email protected]7296f2762011-11-21 19:23:44629struct Invoker;
630
tzikcaf1d84b2016-06-28 12:22:21631template <typename StorageType, typename R, typename... UnboundArgs>
632struct Invoker<StorageType, R(UnboundArgs...)> {
Vladislav Kuzkokov6d208e12017-11-08 21:31:08633 static R RunOnce(BindStateBase* base,
tzik9bc6837b2018-06-28 20:20:47634 PassingType<UnboundArgs>... unbound_args) {
tzik27d1e312016-09-13 05:28:59635 // Local references to make debugger stepping easier. If in a debugger,
636 // you really want to warp ahead and step through the
637 // InvokeHelper<>::MakeItSo() call below.
638 StorageType* storage = static_cast<StorageType*>(base);
639 static constexpr size_t num_bound_args =
640 std::tuple_size<decltype(storage->bound_args_)>::value;
641 return RunImpl(std::move(storage->functor_),
642 std::move(storage->bound_args_),
Jeremy Roman84956fa2017-08-16 15:55:20643 std::make_index_sequence<num_bound_args>(),
tzik27d1e312016-09-13 05:28:59644 std::forward<UnboundArgs>(unbound_args)...);
645 }
646
tzik9bc6837b2018-06-28 20:20:47647 static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
[email protected]7296f2762011-11-21 19:23:44648 // Local references to make debugger stepping easier. If in a debugger,
649 // you really want to warp ahead and step through the
650 // InvokeHelper<>::MakeItSo() call below.
tzikcaf1d84b2016-06-28 12:22:21651 const StorageType* storage = static_cast<StorageType*>(base);
652 static constexpr size_t num_bound_args =
653 std::tuple_size<decltype(storage->bound_args_)>::value;
Jeremy Roman84956fa2017-08-16 15:55:20654 return RunImpl(storage->functor_, storage->bound_args_,
655 std::make_index_sequence<num_bound_args>(),
tzikcaf1d84b2016-06-28 12:22:21656 std::forward<UnboundArgs>(unbound_args)...);
657 }
658
tzik99de02b2016-07-01 05:54:12659 private:
660 template <typename Functor, typename BoundArgsTuple, size_t... indices>
661 static inline R RunImpl(Functor&& functor,
tzikcaf1d84b2016-06-28 12:22:21662 BoundArgsTuple&& bound,
Jeremy Roman84956fa2017-08-16 15:55:20663 std::index_sequence<indices...>,
tzikcaf1d84b2016-06-28 12:22:21664 UnboundArgs&&... unbound_args) {
tzikae4202e2017-07-31 10:41:54665 static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
tzikcaf1d84b2016-06-28 12:22:21666
Jeremy Roman35a317432017-08-16 22:20:53667 using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
tzikcaf1d84b2016-06-28 12:22:21668 static constexpr bool is_weak_call =
669 IsWeakMethod<is_method,
Jeremy Roman35a317432017-08-16 22:20:53670 std::tuple_element_t<indices, DecayedArgsTuple>...>();
tzikcaf1d84b2016-06-28 12:22:21671
tzikee248722016-06-01 08:22:51672 return InvokeHelper<is_weak_call, R>::MakeItSo(
tzik99de02b2016-07-01 05:54:12673 std::forward<Functor>(functor),
tzikf7c47572017-04-05 21:45:03674 Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
tzika43eff02016-03-09 05:46:05675 std::forward<UnboundArgs>(unbound_args)...);
[email protected]fccef1552011-11-28 22:13:54676 }
677};
678
tzikae4202e2017-07-31 10:41:54679// Extracts necessary type info from Functor and BoundArgs.
680// Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
tzikcaf1d84b2016-06-28 12:22:21681template <typename Functor, typename... BoundArgs>
tzikae4202e2017-07-31 10:41:54682struct BindTypeHelper {
683 static constexpr size_t num_bounds = sizeof...(BoundArgs);
684 using FunctorTraits = MakeFunctorTraits<Functor>;
685
686 // Example:
687 // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
688 // is a template pack of `Foo*` and `int16_t`:
689 // - RunType is `double(Foo*, int, const std::string&)`,
690 // - ReturnType is `double`,
691 // - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
692 // - BoundParamsList is `TypeList<Foo*, int>`,
693 // - UnboundParamsList is `TypeList<const std::string&>`,
694 // - BoundArgsList is `TypeList<Foo*, int16_t>`,
695 // - UnboundRunType is `double(const std::string&)`.
696 using RunType = typename FunctorTraits::RunType;
tzikcaf1d84b2016-06-28 12:22:21697 using ReturnType = ExtractReturnType<RunType>;
tzikae4202e2017-07-31 10:41:54698
699 using RunParamsList = ExtractArgs<RunType>;
700 using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
701 using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
702
703 using BoundArgsList = TypeList<BoundArgs...>;
704
705 using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
tzikcaf1d84b2016-06-28 12:22:21706};
tzikae4202e2017-07-31 10:41:54707
tzikc1db72652016-07-08 09:42:38708template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53709std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
710 const Functor& functor) {
tzikc1db72652016-07-08 09:42:38711 return !functor;
712}
713
714template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53715std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
716 const Functor&) {
tzikc1db72652016-07-08 09:42:38717 return false;
718}
tzikcaf1d84b2016-06-28 12:22:21719
tzik9697d49e2018-08-02 13:35:19720// Used by QueryCancellationTraits below.
tzik6c92eab2016-11-25 15:56:36721template <typename Functor, typename BoundArgsTuple, size_t... indices>
tzik9697d49e2018-08-02 13:35:19722bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
723 const Functor& functor,
724 const BoundArgsTuple& bound_args,
725 std::index_sequence<indices...>) {
726 switch (mode) {
727 case BindStateBase::IS_CANCELLED:
728 return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
729 functor, std::get<indices>(bound_args)...);
730 case BindStateBase::MAYBE_VALID:
731 return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
732 functor, std::get<indices>(bound_args)...);
733 }
734 NOTREACHED();
tzik6c92eab2016-11-25 15:56:36735}
tzik59aa6bb12016-09-08 10:58:53736
tzik6c92eab2016-11-25 15:56:36737// Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
738// true if the callback |base| represents is canceled.
739template <typename BindStateType>
tzik9697d49e2018-08-02 13:35:19740bool QueryCancellationTraits(const BindStateBase* base,
741 BindStateBase::CancellationQueryMode mode) {
tzik6c92eab2016-11-25 15:56:36742 const BindStateType* storage = static_cast<const BindStateType*>(base);
743 static constexpr size_t num_bound_args =
744 std::tuple_size<decltype(storage->bound_args_)>::value;
tzik9697d49e2018-08-02 13:35:19745 return QueryCancellationTraitsImpl(
746 mode, storage->functor_, storage->bound_args_,
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:48747 std::make_index_sequence<num_bound_args>());
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:48748}
749
tzikefea4f52018-08-02 15:20:46750// The base case of BanUnconstructedRefCountedReceiver that checks nothing.
751template <typename Functor, typename Receiver, typename... Unused>
752std::enable_if_t<
753 !(MakeFunctorTraits<Functor>::is_method &&
754 std::is_pointer<std::decay_t<Receiver>>::value &&
755 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
756BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
757
758template <typename Functor>
759void BanUnconstructedRefCountedReceiver() {}
760
761// Asserts that Callback is not the first owner of a ref-counted receiver.
762template <typename Functor, typename Receiver, typename... Unused>
763std::enable_if_t<
764 MakeFunctorTraits<Functor>::is_method &&
765 std::is_pointer<std::decay_t<Receiver>>::value &&
766 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
767BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
768 DCHECK(receiver);
769
770 // It's error prone to make the implicit first reference to ref-counted types.
771 // In the example below, base::BindOnce() makes the implicit first reference
772 // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
773 // enough, the newly created instance can be destroyed before |oo| makes
774 // another reference.
775 // Foo::Foo() {
776 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
777 // }
778 //
779 // scoped_refptr<Foo> oo = new Foo();
780 //
781 // Instead of doing like above, please consider adding a static constructor,
782 // and keep the first reference alive explicitly.
783 // // static
784 // scoped_refptr<Foo> Foo::Create() {
785 // auto foo = base::WrapRefCounted(new Foo());
786 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
787 // return foo;
788 // }
789 //
790 // Foo::Foo() {}
791 //
792 // scoped_refptr<Foo> oo = Foo::Create();
793 DCHECK(receiver->HasAtLeastOneRef())
kylechar2255ccc2019-09-11 21:47:23794 << "base::Bind{Once,Repeating}() refuses to create the first reference "
795 "to ref-counted objects. That typically happens around PostTask() in "
796 "their constructor, and such objects can be destroyed before `new` "
797 "returns if the task resolves fast enough.";
tzikefea4f52018-08-02 15:20:46798}
799
[email protected]7296f2762011-11-21 19:23:44800// BindState<>
801//
tzik99de02b2016-07-01 05:54:12802// This stores all the state passed into Bind().
803template <typename Functor, typename... BoundArgs>
804struct BindState final : BindStateBase {
tzik1fdcca32016-09-14 07:15:00805 using IsCancellable = std::integral_constant<
tzik6c92eab2016-11-25 15:56:36806 bool,
807 CallbackCancellationTraits<Functor,
808 std::tuple<BoundArgs...>>::is_cancellable>;
tzik1fdcca32016-09-14 07:15:00809
tzikbfe66122016-07-08 14:14:01810 template <typename ForwardFunctor, typename... ForwardBoundArgs>
tzikefea4f52018-08-02 15:20:46811 static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
812 ForwardFunctor&& functor,
813 ForwardBoundArgs&&... bound_args) {
814 // Ban ref counted receivers that were not yet fully constructed to avoid
815 // a common pattern of racy situation.
816 BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
817
818 // IsCancellable is std::false_type if
819 // CallbackCancellationTraits<>::IsCancelled returns always false.
820 // Otherwise, it's std::true_type.
821 return new BindState(IsCancellable{}, invoke_func,
822 std::forward<ForwardFunctor>(functor),
823 std::forward<ForwardBoundArgs>(bound_args)...);
824 }
tzik1fdcca32016-09-14 07:15:00825
826 Functor functor_;
827 std::tuple<BoundArgs...> bound_args_;
828
829 private:
830 template <typename ForwardFunctor, typename... ForwardBoundArgs>
831 explicit BindState(std::true_type,
832 BindStateBase::InvokeFuncStorage invoke_func,
833 ForwardFunctor&& functor,
834 ForwardBoundArgs&&... bound_args)
tzik6c92eab2016-11-25 15:56:36835 : BindStateBase(invoke_func,
836 &Destroy,
tzik9697d49e2018-08-02 13:35:19837 &QueryCancellationTraits<BindState>),
tzikff54a5b152016-08-31 11:50:41838 functor_(std::forward<ForwardFunctor>(functor)),
tzik99de02b2016-07-01 05:54:12839 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
tzikc1db72652016-07-08 09:42:38840 DCHECK(!IsNull(functor_));
tzik99de02b2016-07-01 05:54:12841 }
[email protected]7296f2762011-11-21 19:23:44842
tzik1fdcca32016-09-14 07:15:00843 template <typename ForwardFunctor, typename... ForwardBoundArgs>
844 explicit BindState(std::false_type,
845 BindStateBase::InvokeFuncStorage invoke_func,
846 ForwardFunctor&& functor,
847 ForwardBoundArgs&&... bound_args)
848 : BindStateBase(invoke_func, &Destroy),
849 functor_(std::forward<ForwardFunctor>(functor)),
850 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
851 DCHECK(!IsNull(functor_));
852 }
dmichael7d09007e2014-12-18 22:30:11853
Chris Watkins091d6292017-12-13 04:25:58854 ~BindState() = default;
taptede7e804c2015-05-14 08:03:32855
tzik30e0c312016-09-21 08:06:54856 static void Destroy(const BindStateBase* self) {
857 delete static_cast<const BindState*>(self);
taptede7e804c2015-05-14 08:03:32858 }
[email protected]fccef1552011-11-28 22:13:54859};
860
tzik99de02b2016-07-01 05:54:12861// Used to implement MakeBindStateType.
862template <bool is_method, typename Functor, typename... BoundArgs>
863struct MakeBindStateTypeImpl;
864
865template <typename Functor, typename... BoundArgs>
866struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
Jeremy Roman35a317432017-08-16 22:20:53867 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
tzik99de02b2016-07-01 05:54:12868 "A parameter is a refcounted type and needs scoped_refptr.");
Jeremy Roman35a317432017-08-16 22:20:53869 using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
tzik99de02b2016-07-01 05:54:12870};
871
872template <typename Functor>
873struct MakeBindStateTypeImpl<true, Functor> {
Jeremy Roman35a317432017-08-16 22:20:53874 using Type = BindState<std::decay_t<Functor>>;
tzik99de02b2016-07-01 05:54:12875};
876
877template <typename Functor, typename Receiver, typename... BoundArgs>
878struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
tzik99de02b2016-07-01 05:54:12879 private:
Jeremy Roman35a317432017-08-16 22:20:53880 using DecayedReceiver = std::decay_t<Receiver>;
tzik99de02b2016-07-01 05:54:12881
tzik4625ac612018-02-28 09:43:55882 static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
883 "First bound argument to a method cannot be an array.");
884 static_assert(
885 !std::is_pointer<DecayedReceiver>::value ||
886 IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
887 "Receivers may not be raw pointers. If using a raw pointer here is safe"
888 " and has no lifetime concerns, use base::Unretained() and document why"
889 " it's safe.");
890 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
891 "A parameter is a refcounted type and needs scoped_refptr.");
892
tzik99de02b2016-07-01 05:54:12893 public:
894 using Type = BindState<
Jeremy Roman35a317432017-08-16 22:20:53895 std::decay_t<Functor>,
896 std::conditional_t<std::is_pointer<DecayedReceiver>::value,
897 scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
898 DecayedReceiver>,
899 std::decay_t<BoundArgs>...>;
tzik99de02b2016-07-01 05:54:12900};
901
902template <typename Functor, typename... BoundArgs>
tzikae4202e2017-07-31 10:41:54903using MakeBindStateType =
904 typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
905 Functor,
906 BoundArgs...>::Type;
tzik99de02b2016-07-01 05:54:12907
[email protected]b38d3572011-02-15 01:27:38908} // namespace internal
tzikcaf1d84b2016-06-28 12:22:21909
Peter Kastinga85265e32018-02-15 08:30:23910// An injection point to control |this| pointer behavior on a method invocation.
911// If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
912// method, base::Bind cancels the method invocation if the receiver is tested as
913// false.
914// E.g. Foo::bar() is not called:
915// struct Foo : base::SupportsWeakPtr<Foo> {
916// void bar() {}
917// };
918//
919// WeakPtr<Foo> oo = nullptr;
kylechar2255ccc2019-09-11 21:47:23920// base::BindOnce(&Foo::bar, oo).Run();
Peter Kastinga85265e32018-02-15 08:30:23921template <typename T>
922struct IsWeakReceiver : std::false_type {};
923
924template <typename T>
jdoerriec79c2fa22019-02-26 12:35:03925struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
Peter Kastinga85265e32018-02-15 08:30:23926
927template <typename T>
928struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
929
930// An injection point to control how bound objects passed to the target
931// function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
932// before the target function is invoked.
933template <typename>
934struct BindUnwrapTraits {
935 template <typename T>
936 static T&& Unwrap(T&& o) {
937 return std::forward<T>(o);
938 }
939};
940
941template <typename T>
942struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
943 static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
944};
945
946template <typename T>
jdoerriec79c2fa22019-02-26 12:35:03947struct BindUnwrapTraits<std::reference_wrapper<T>> {
948 static T& Unwrap(std::reference_wrapper<T> o) { return o.get(); }
Peter Kastinga85265e32018-02-15 08:30:23949};
950
951template <typename T>
952struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
953 static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
954};
955
Marijn Kruisselbrinkc1e775f2019-12-19 01:24:22956template <typename T, typename Deleter>
957struct BindUnwrapTraits<internal::OwnedWrapper<T, Deleter>> {
958 static T* Unwrap(const internal::OwnedWrapper<T, Deleter>& o) {
959 return o.get();
960 }
Peter Kastinga85265e32018-02-15 08:30:23961};
962
963template <typename T>
964struct BindUnwrapTraits<internal::PassedWrapper<T>> {
965 static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
966};
967
tzikc44f8102018-07-24 09:49:19968#if defined(OS_WIN)
969template <typename T>
970struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
971 static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
972};
973#endif
974
Peter Kastinga85265e32018-02-15 08:30:23975// CallbackCancellationTraits allows customization of Callback's cancellation
976// semantics. By default, callbacks are not cancellable. A specialization should
977// set is_cancellable = true and implement an IsCancelled() that returns if the
978// callback should be cancelled.
979template <typename Functor, typename BoundArgsTuple, typename SFINAE>
980struct CallbackCancellationTraits {
981 static constexpr bool is_cancellable = false;
982};
983
984// Specialization for method bound to weak pointer receiver.
985template <typename Functor, typename... BoundArgs>
986struct CallbackCancellationTraits<
987 Functor,
988 std::tuple<BoundArgs...>,
989 std::enable_if_t<
990 internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
991 BoundArgs...>::value>> {
992 static constexpr bool is_cancellable = true;
993
994 template <typename Receiver, typename... Args>
995 static bool IsCancelled(const Functor&,
996 const Receiver& receiver,
997 const Args&...) {
998 return !receiver;
999 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:481000
1001 template <typename Receiver, typename... Args>
1002 static bool MaybeValid(const Functor&,
1003 const Receiver& receiver,
1004 const Args&...) {
1005 return receiver.MaybeValid();
1006 }
Peter Kastinga85265e32018-02-15 08:30:231007};
1008
1009// Specialization for a nested bind.
1010template <typename Signature, typename... BoundArgs>
1011struct CallbackCancellationTraits<OnceCallback<Signature>,
1012 std::tuple<BoundArgs...>> {
1013 static constexpr bool is_cancellable = true;
1014
1015 template <typename Functor>
1016 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1017 return functor.IsCancelled();
1018 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:481019
1020 template <typename Functor>
1021 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1022 return functor.MaybeValid();
1023 }
Peter Kastinga85265e32018-02-15 08:30:231024};
1025
1026template <typename Signature, typename... BoundArgs>
1027struct CallbackCancellationTraits<RepeatingCallback<Signature>,
1028 std::tuple<BoundArgs...>> {
1029 static constexpr bool is_cancellable = true;
1030
1031 template <typename Functor>
1032 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1033 return functor.IsCancelled();
1034 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:481035
1036 template <typename Functor>
1037 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1038 return functor.MaybeValid();
1039 }
Peter Kastinga85265e32018-02-15 08:30:231040};
1041
tzikcaf1d84b2016-06-28 12:22:211042// Returns a RunType of bound functor.
1043// E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
1044template <typename Functor, typename... BoundArgs>
1045using MakeUnboundRunType =
tzikae4202e2017-07-31 10:41:541046 typename internal::BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
tzikcaf1d84b2016-06-28 12:22:211047
[email protected]b38d3572011-02-15 01:27:381048} // namespace base
1049
1050#endif // BASE_BIND_INTERNAL_H_