blob: 02c06b7b58452a606acb05b94325828e6a52e332 [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
Peter Kastinga85265e32018-02-15 08:30:23107template <typename T>
108class OwnedWrapper {
109 public:
110 explicit OwnedWrapper(T* o) : ptr_(o) {}
jdoerrie68f2d51b2019-02-28 17:32:44111 explicit OwnedWrapper(std::unique_ptr<T>&& ptr) : ptr_(std::move(ptr)) {}
112 T* get() const { return ptr_.get(); }
Peter Kastinga85265e32018-02-15 08:30:23113
114 private:
jdoerrie68f2d51b2019-02-28 17:32:44115 std::unique_ptr<T> ptr_;
Peter Kastinga85265e32018-02-15 08:30:23116};
117
118// PassedWrapper is a copyable adapter for a scoper that ignores const.
119//
120// It is needed to get around the fact that Bind() takes a const reference to
121// all its arguments. Because Bind() takes a const reference to avoid
122// unnecessary copies, it is incompatible with movable-but-not-copyable
123// types; doing a destructive "move" of the type into Bind() would violate
124// the const correctness.
125//
126// This conundrum cannot be solved without either C++11 rvalue references or
127// a O(2^n) blowup of Bind() templates to handle each combination of regular
128// types and movable-but-not-copyable types. Thus we introduce a wrapper type
129// that is copyable to transmit the correct type information down into
130// BindState<>. Ignoring const in this type makes sense because it is only
131// created when we are explicitly trying to do a destructive move.
132//
133// Two notes:
134// 1) PassedWrapper supports any type that has a move constructor, however
135// the type will need to be specifically whitelisted in order for it to be
136// bound to a Callback. We guard this explicitly at the call of Passed()
137// to make for clear errors. Things not given to Passed() will be forwarded
138// and stored by value which will not work for general move-only types.
139// 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
140// scoper to a Callback and allow the Callback to execute once.
141template <typename T>
142class PassedWrapper {
143 public:
144 explicit PassedWrapper(T&& scoper)
145 : is_valid_(true), scoper_(std::move(scoper)) {}
146 PassedWrapper(PassedWrapper&& other)
147 : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
148 T Take() const {
149 CHECK(is_valid_);
150 is_valid_ = false;
151 return std::move(scoper_);
152 }
153
154 private:
155 mutable bool is_valid_;
156 mutable T scoper_;
157};
158
159template <typename T>
160using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
161
162template <typename T>
Peter Kastingc2f8749bf2018-03-31 03:32:37163decltype(auto) Unwrap(T&& o) {
Peter Kastinga85265e32018-02-15 08:30:23164 return Unwrapper<T>::Unwrap(std::forward<T>(o));
165}
166
167// IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
168// method. It is used internally by Bind() to select the correct
169// InvokeHelper that will no-op itself in the event the WeakPtr<> for
170// the target object is invalidated.
171//
172// The first argument should be the type of the object that will be received by
173// the method.
174template <bool is_method, typename... Args>
175struct IsWeakMethod : std::false_type {};
176
177template <typename T, typename... Args>
178struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
179
180// Packs a list of types to hold them in a single type.
181template <typename... Types>
182struct TypeList {};
183
184// Used for DropTypeListItem implementation.
185template <size_t n, typename List>
186struct DropTypeListItemImpl;
187
188// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
189template <size_t n, typename T, typename... List>
190struct DropTypeListItemImpl<n, TypeList<T, List...>>
191 : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
192
193template <typename T, typename... List>
194struct DropTypeListItemImpl<0, TypeList<T, List...>> {
195 using Type = TypeList<T, List...>;
196};
197
198template <>
199struct DropTypeListItemImpl<0, TypeList<>> {
200 using Type = TypeList<>;
201};
202
203// A type-level function that drops |n| list item from given TypeList.
204template <size_t n, typename List>
205using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
206
207// Used for TakeTypeListItem implementation.
208template <size_t n, typename List, typename... Accum>
209struct TakeTypeListItemImpl;
210
211// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
212template <size_t n, typename T, typename... List, typename... Accum>
213struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
214 : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
215
216template <typename T, typename... List, typename... Accum>
217struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
218 using Type = TypeList<Accum...>;
219};
220
221template <typename... Accum>
222struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
223 using Type = TypeList<Accum...>;
224};
225
226// A type-level function that takes first |n| list item from given TypeList.
227// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
228// TypeList<A, B, C>.
229template <size_t n, typename List>
230using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
231
232// Used for ConcatTypeLists implementation.
233template <typename List1, typename List2>
234struct ConcatTypeListsImpl;
235
236template <typename... Types1, typename... Types2>
237struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
238 using Type = TypeList<Types1..., Types2...>;
239};
240
241// A type-level function that concats two TypeLists.
242template <typename List1, typename List2>
243using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
244
245// Used for MakeFunctionType implementation.
246template <typename R, typename ArgList>
247struct MakeFunctionTypeImpl;
248
249template <typename R, typename... Args>
250struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
251 // MSVC 2013 doesn't support Type Alias of function types.
252 // Revisit this after we update it to newer version.
253 typedef R Type(Args...);
254};
255
256// A type-level function that constructs a function type that has |R| as its
257// return type and has TypeLists items as its arguments.
258template <typename R, typename ArgList>
259using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
260
261// Used for ExtractArgs and ExtractReturnType.
262template <typename Signature>
263struct ExtractArgsImpl;
264
265template <typename R, typename... Args>
266struct ExtractArgsImpl<R(Args...)> {
267 using ReturnType = R;
268 using ArgsList = TypeList<Args...>;
269};
270
271// A type-level function that extracts function arguments into a TypeList.
272// E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
273template <typename Signature>
274using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
275
276// A type-level function that extracts the return type of a function.
277// E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
278template <typename Signature>
279using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
280
tzikc1db72652016-07-08 09:42:38281template <typename Callable,
282 typename Signature = decltype(&Callable::operator())>
283struct ExtractCallableRunTypeImpl;
284
285template <typename Callable, typename R, typename... Args>
tzikf98654b2017-12-02 03:28:58286struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
287 using Type = R(Args...);
288};
289
290template <typename Callable, typename R, typename... Args>
291struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...) const> {
tzikc1db72652016-07-08 09:42:38292 using Type = R(Args...);
293};
294
295// Evaluated to RunType of the given callable type.
296// Example:
297// auto f = [](int, char*) { return 0.1; };
298// ExtractCallableRunType<decltype(f)>
299// is evaluated to
300// double(int, char*);
301template <typename Callable>
302using ExtractCallableRunType =
303 typename ExtractCallableRunTypeImpl<Callable>::Type;
304
tzikf98654b2017-12-02 03:28:58305// IsCallableObject<Functor> is std::true_type if |Functor| has operator().
306// Otherwise, it's std::false_type.
tzikc1db72652016-07-08 09:42:38307// Example:
tzikf98654b2017-12-02 03:28:58308// IsCallableObject<void(*)()>::value is false.
tzikc1db72652016-07-08 09:42:38309//
310// struct Foo {};
tzikf98654b2017-12-02 03:28:58311// IsCallableObject<void(Foo::*)()>::value is false.
tzikc1db72652016-07-08 09:42:38312//
313// int i = 0;
tzikf98654b2017-12-02 03:28:58314// auto f = [i]() {};
315// IsCallableObject<decltype(f)>::value is false.
tzikc1db72652016-07-08 09:42:38316template <typename Functor, typename SFINAE = void>
tzikf98654b2017-12-02 03:28:58317struct IsCallableObject : std::false_type {};
tzikc1db72652016-07-08 09:42:38318
319template <typename Callable>
tzikf98654b2017-12-02 03:28:58320struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
321 : std::true_type {};
tzikc1db72652016-07-08 09:42:38322
tzik401dd3672014-11-26 07:54:58323// HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
324// pointer to a RefCounted type.
325// Implementation note: This non-specialized case handles zero-arity case only.
326// Non-zero-arity cases should be handled by the specialization below.
327template <typename... Args>
tzik403cb6c2016-03-10 07:17:25328struct HasRefCountedTypeAsRawPtr : std::false_type {};
tzik401dd3672014-11-26 07:54:58329
330// Implementation note: Select true_type if the first parameter is a raw pointer
331// to a RefCounted type. Otherwise, skip the first parameter and check rest of
332// parameters recursively.
333template <typename T, typename... Args>
334struct HasRefCountedTypeAsRawPtr<T, Args...>
Jeremy Roman35a317432017-08-16 22:20:53335 : std::conditional_t<NeedsScopedRefptrButGetsRawPtr<T>::value,
336 std::true_type,
337 HasRefCountedTypeAsRawPtr<Args...>> {};
tzik401dd3672014-11-26 07:54:58338
[email protected]7296f2762011-11-21 19:23:44339// ForceVoidReturn<>
340//
341// Set of templates that support forcing the function return type to void.
342template <typename Sig>
343struct ForceVoidReturn;
344
tzikc82149922014-11-20 10:09:45345template <typename R, typename... Args>
346struct ForceVoidReturn<R(Args...)> {
tzik99de02b2016-07-01 05:54:12347 using RunType = void(Args...);
[email protected]fccef1552011-11-28 22:13:54348};
349
[email protected]7296f2762011-11-21 19:23:44350// FunctorTraits<>
351//
352// See description at top of file.
tzik6c92eab2016-11-25 15:56:36353template <typename Functor, typename SFINAE>
tzik99de02b2016-07-01 05:54:12354struct FunctorTraits;
355
tzikf98654b2017-12-02 03:28:58356// For empty callable types.
kylechar2255ccc2019-09-11 21:47:23357// This specialization is intended to allow binding captureless lambdas, based
358// on the fact that captureless lambdas are empty while capturing lambdas are
359// not. This also allows any functors as far as it's an empty class.
tzikf98654b2017-12-02 03:28:58360// Example:
361//
362// // Captureless lambdas are allowed.
363// []() {return 42;};
364//
365// // Capturing lambdas are *not* allowed.
366// int x;
367// [x]() {return x;};
368//
369// // Any empty class with operator() is allowed.
370// struct Foo {
371// void operator()() const {}
372// // No non-static member variable and no virtual functions.
373// };
tzikc1db72652016-07-08 09:42:38374template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53375struct FunctorTraits<Functor,
tzikf98654b2017-12-02 03:28:58376 std::enable_if_t<IsCallableObject<Functor>::value &&
377 std::is_empty<Functor>::value>> {
tzikc1db72652016-07-08 09:42:38378 using RunType = ExtractCallableRunType<Functor>;
379 static constexpr bool is_method = false;
380 static constexpr bool is_nullable = false;
381
tzikf98654b2017-12-02 03:28:58382 template <typename RunFunctor, typename... RunArgs>
383 static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
384 RunArgs&&... args) {
385 return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
tzikc1db72652016-07-08 09:42:38386 }
387};
388
tzik99de02b2016-07-01 05:54:12389// For functions.
390template <typename R, typename... Args>
391struct FunctorTraits<R (*)(Args...)> {
392 using RunType = R(Args...);
393 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38394 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12395
tzikd58a89232018-04-26 04:29:53396 template <typename Function, typename... RunArgs>
397 static R Invoke(Function&& function, RunArgs&&... args) {
398 return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12399 }
[email protected]7296f2762011-11-21 19:23:44400};
401
Gaurav Dholf6e3f592018-10-29 17:22:41402#if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
tzik99de02b2016-07-01 05:54:12403
404// For functions.
405template <typename R, typename... Args>
406struct FunctorTraits<R(__stdcall*)(Args...)> {
407 using RunType = R(Args...);
408 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38409 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12410
411 template <typename... RunArgs>
412 static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
413 return function(std::forward<RunArgs>(args)...);
414 }
415};
416
417// For functions.
418template <typename R, typename... Args>
419struct FunctorTraits<R(__fastcall*)(Args...)> {
420 using RunType = R(Args...);
421 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38422 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12423
424 template <typename... RunArgs>
425 static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
426 return function(std::forward<RunArgs>(args)...);
427 }
428};
429
Gaurav Dholf6e3f592018-10-29 17:22:41430#endif // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
tzik99de02b2016-07-01 05:54:12431
Sylvain Defresneec3270c2018-05-31 17:19:15432#if defined(OS_MACOSX)
433
434// Support for Objective-C blocks. There are two implementation depending
435// on whether Automated Reference Counting (ARC) is enabled. When ARC is
436// enabled, then the block itself can be bound as the compiler will ensure
437// its lifetime will be correctly managed. Otherwise, require the block to
438// be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
439// correctly manage the block lifetime.
440//
441// The two implementation ensure that the One Definition Rule (ODR) is not
442// broken (it is not possible to write a template base::RetainBlock that would
443// work correctly both with ARC enabled and disabled).
444
445#if HAS_FEATURE(objc_arc)
446
447template <typename R, typename... Args>
448struct FunctorTraits<R (^)(Args...)> {
449 using RunType = R(Args...);
450 static constexpr bool is_method = false;
451 static constexpr bool is_nullable = true;
452
453 template <typename BlockType, typename... RunArgs>
454 static R Invoke(BlockType&& block, RunArgs&&... args) {
455 // According to LLVM documentation (§ 6.3), "local variables of automatic
456 // storage duration do not have precise lifetime." Use objc_precise_lifetime
457 // to ensure that the Objective-C block is not deallocated until it has
458 // finished executing even if the Callback<> is destroyed during the block
459 // execution.
460 // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
461 __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
462 return scoped_block(std::forward<RunArgs>(args)...);
463 }
464};
465
466#else // HAS_FEATURE(objc_arc)
467
468template <typename R, typename... Args>
469struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
470 using RunType = R(Args...);
471 static constexpr bool is_method = false;
472 static constexpr bool is_nullable = true;
473
474 template <typename BlockType, typename... RunArgs>
475 static R Invoke(BlockType&& block, RunArgs&&... args) {
476 // Copy the block to ensure that the Objective-C block is not deallocated
477 // until it has finished executing even if the Callback<> is destroyed
478 // during the block execution.
479 base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
480 return scoped_block.get()(std::forward<RunArgs>(args)...);
481 }
482};
483
484#endif // HAS_FEATURE(objc_arc)
485#endif // defined(OS_MACOSX)
486
tzik99de02b2016-07-01 05:54:12487// For methods.
488template <typename R, typename Receiver, typename... Args>
489struct FunctorTraits<R (Receiver::*)(Args...)> {
490 using RunType = R(Receiver*, Args...);
491 static constexpr bool is_method = true;
tzikc1db72652016-07-08 09:42:38492 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12493
tzikd58a89232018-04-26 04:29:53494 template <typename Method, typename ReceiverPtr, typename... RunArgs>
495 static R Invoke(Method method,
tzik99de02b2016-07-01 05:54:12496 ReceiverPtr&& receiver_ptr,
497 RunArgs&&... args) {
tzik75851f42017-06-14 06:57:01498 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12499 }
500};
501
502// For const methods.
503template <typename R, typename Receiver, typename... Args>
504struct FunctorTraits<R (Receiver::*)(Args...) const> {
505 using RunType = R(const Receiver*, Args...);
506 static constexpr bool is_method = true;
tzikc1db72652016-07-08 09:42:38507 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12508
tzikd58a89232018-04-26 04:29:53509 template <typename Method, typename ReceiverPtr, typename... RunArgs>
510 static R Invoke(Method method,
tzik99de02b2016-07-01 05:54:12511 ReceiverPtr&& receiver_ptr,
512 RunArgs&&... args) {
tzik75851f42017-06-14 06:57:01513 return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12514 }
515};
516
tzikd58a89232018-04-26 04:29:53517#ifdef __cpp_noexcept_function_type
518// noexcept makes a distinct function type in C++17.
519// I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
520// different in C++17.
521template <typename R, typename... Args>
522struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
523};
524
525template <typename R, typename Receiver, typename... Args>
526struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
527 : FunctorTraits<R (Receiver::*)(Args...)> {};
528
529template <typename R, typename Receiver, typename... Args>
530struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
531 : FunctorTraits<R (Receiver::*)(Args...) const> {};
532#endif
533
tzik99de02b2016-07-01 05:54:12534// For IgnoreResults.
[email protected]7296f2762011-11-21 19:23:44535template <typename T>
tzik99de02b2016-07-01 05:54:12536struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
tzik3bc7779b2015-12-19 09:18:46537 using RunType =
tzik99de02b2016-07-01 05:54:12538 typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
539
540 template <typename IgnoreResultType, typename... RunArgs>
541 static void Invoke(IgnoreResultType&& ignore_result_helper,
542 RunArgs&&... args) {
tzikff54a5b152016-08-31 11:50:41543 FunctorTraits<T>::Invoke(
544 std::forward<IgnoreResultType>(ignore_result_helper).functor_,
545 std::forward<RunArgs>(args)...);
tzik99de02b2016-07-01 05:54:12546 }
[email protected]7296f2762011-11-21 19:23:44547};
548
tzikd4bb5b7d2017-08-28 19:08:52549// For OnceCallbacks.
550template <typename R, typename... Args>
551struct FunctorTraits<OnceCallback<R(Args...)>> {
552 using RunType = R(Args...);
553 static constexpr bool is_method = false;
554 static constexpr bool is_nullable = true;
555
556 template <typename CallbackType, typename... RunArgs>
557 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
558 DCHECK(!callback.is_null());
559 return std::forward<CallbackType>(callback).Run(
560 std::forward<RunArgs>(args)...);
561 }
562};
563
564// For RepeatingCallbacks.
565template <typename R, typename... Args>
566struct FunctorTraits<RepeatingCallback<R(Args...)>> {
tzik99de02b2016-07-01 05:54:12567 using RunType = R(Args...);
568 static constexpr bool is_method = false;
tzikc1db72652016-07-08 09:42:38569 static constexpr bool is_nullable = true;
tzik99de02b2016-07-01 05:54:12570
571 template <typename CallbackType, typename... RunArgs>
572 static R Invoke(CallbackType&& callback, RunArgs&&... args) {
573 DCHECK(!callback.is_null());
574 return std::forward<CallbackType>(callback).Run(
575 std::forward<RunArgs>(args)...);
576 }
[email protected]7296f2762011-11-21 19:23:44577};
578
tzikae4202e2017-07-31 10:41:54579template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53580using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
tzikae4202e2017-07-31 10:41:54581
[email protected]7296f2762011-11-21 19:23:44582// InvokeHelper<>
583//
tzik99de02b2016-07-01 05:54:12584// There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
[email protected]7296f2762011-11-21 19:23:44585//
586// The normal type just calls the underlying runnable.
587//
tzik99de02b2016-07-01 05:54:12588// WeakCalls need special syntax that is applied to the first argument to check
589// if they should no-op themselves.
tzikee248722016-06-01 08:22:51590template <bool is_weak_call, typename ReturnType>
[email protected]7296f2762011-11-21 19:23:44591struct InvokeHelper;
592
tzikee248722016-06-01 08:22:51593template <typename ReturnType>
594struct InvokeHelper<false, ReturnType> {
tzik99de02b2016-07-01 05:54:12595 template <typename Functor, typename... RunArgs>
596 static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
tzikae4202e2017-07-31 10:41:54597 using Traits = MakeFunctorTraits<Functor>;
tzik99de02b2016-07-01 05:54:12598 return Traits::Invoke(std::forward<Functor>(functor),
599 std::forward<RunArgs>(args)...);
[email protected]7296f2762011-11-21 19:23:44600 }
601};
602
tzikee248722016-06-01 08:22:51603template <typename ReturnType>
604struct InvokeHelper<true, ReturnType> {
[email protected]7296f2762011-11-21 19:23:44605 // WeakCalls are only supported for functions with a void return type.
606 // Otherwise, the function result would be undefined if the the WeakPtr<>
607 // is invalidated.
tzik403cb6c2016-03-10 07:17:25608 static_assert(std::is_void<ReturnType>::value,
avi4ec0dff2015-11-24 14:26:24609 "weak_ptrs can only bind to methods without return values");
[email protected]c18b1052011-03-24 02:02:17610
tzik99de02b2016-07-01 05:54:12611 template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
612 static inline void MakeItSo(Functor&& functor,
tzik33871d82016-07-14 12:12:06613 BoundWeakPtr&& weak_ptr,
tzik99de02b2016-07-01 05:54:12614 RunArgs&&... args) {
615 if (!weak_ptr)
616 return;
tzikae4202e2017-07-31 10:41:54617 using Traits = MakeFunctorTraits<Functor>;
tzik99de02b2016-07-01 05:54:12618 Traits::Invoke(std::forward<Functor>(functor),
619 std::forward<BoundWeakPtr>(weak_ptr),
620 std::forward<RunArgs>(args)...);
621 }
622};
[email protected]b38d3572011-02-15 01:27:38623
[email protected]7296f2762011-11-21 19:23:44624// Invoker<>
625//
626// See description at the top of the file.
tzikcaf1d84b2016-06-28 12:22:21627template <typename StorageType, typename UnboundRunType>
[email protected]7296f2762011-11-21 19:23:44628struct Invoker;
629
tzikcaf1d84b2016-06-28 12:22:21630template <typename StorageType, typename R, typename... UnboundArgs>
631struct Invoker<StorageType, R(UnboundArgs...)> {
Vladislav Kuzkokov6d208e12017-11-08 21:31:08632 static R RunOnce(BindStateBase* base,
tzik9bc6837b2018-06-28 20:20:47633 PassingType<UnboundArgs>... unbound_args) {
tzik27d1e312016-09-13 05:28:59634 // Local references to make debugger stepping easier. If in a debugger,
635 // you really want to warp ahead and step through the
636 // InvokeHelper<>::MakeItSo() call below.
637 StorageType* storage = static_cast<StorageType*>(base);
638 static constexpr size_t num_bound_args =
639 std::tuple_size<decltype(storage->bound_args_)>::value;
640 return RunImpl(std::move(storage->functor_),
641 std::move(storage->bound_args_),
Jeremy Roman84956fa2017-08-16 15:55:20642 std::make_index_sequence<num_bound_args>(),
tzik27d1e312016-09-13 05:28:59643 std::forward<UnboundArgs>(unbound_args)...);
644 }
645
tzik9bc6837b2018-06-28 20:20:47646 static R Run(BindStateBase* base, PassingType<UnboundArgs>... unbound_args) {
[email protected]7296f2762011-11-21 19:23:44647 // Local references to make debugger stepping easier. If in a debugger,
648 // you really want to warp ahead and step through the
649 // InvokeHelper<>::MakeItSo() call below.
tzikcaf1d84b2016-06-28 12:22:21650 const StorageType* storage = static_cast<StorageType*>(base);
651 static constexpr size_t num_bound_args =
652 std::tuple_size<decltype(storage->bound_args_)>::value;
Jeremy Roman84956fa2017-08-16 15:55:20653 return RunImpl(storage->functor_, storage->bound_args_,
654 std::make_index_sequence<num_bound_args>(),
tzikcaf1d84b2016-06-28 12:22:21655 std::forward<UnboundArgs>(unbound_args)...);
656 }
657
tzik99de02b2016-07-01 05:54:12658 private:
659 template <typename Functor, typename BoundArgsTuple, size_t... indices>
660 static inline R RunImpl(Functor&& functor,
tzikcaf1d84b2016-06-28 12:22:21661 BoundArgsTuple&& bound,
Jeremy Roman84956fa2017-08-16 15:55:20662 std::index_sequence<indices...>,
tzikcaf1d84b2016-06-28 12:22:21663 UnboundArgs&&... unbound_args) {
tzikae4202e2017-07-31 10:41:54664 static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
tzikcaf1d84b2016-06-28 12:22:21665
Jeremy Roman35a317432017-08-16 22:20:53666 using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
tzikcaf1d84b2016-06-28 12:22:21667 static constexpr bool is_weak_call =
668 IsWeakMethod<is_method,
Jeremy Roman35a317432017-08-16 22:20:53669 std::tuple_element_t<indices, DecayedArgsTuple>...>();
tzikcaf1d84b2016-06-28 12:22:21670
tzikee248722016-06-01 08:22:51671 return InvokeHelper<is_weak_call, R>::MakeItSo(
tzik99de02b2016-07-01 05:54:12672 std::forward<Functor>(functor),
tzikf7c47572017-04-05 21:45:03673 Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
tzika43eff02016-03-09 05:46:05674 std::forward<UnboundArgs>(unbound_args)...);
[email protected]fccef1552011-11-28 22:13:54675 }
676};
677
tzikae4202e2017-07-31 10:41:54678// Extracts necessary type info from Functor and BoundArgs.
679// Used to implement MakeUnboundRunType, BindOnce and BindRepeating.
tzikcaf1d84b2016-06-28 12:22:21680template <typename Functor, typename... BoundArgs>
tzikae4202e2017-07-31 10:41:54681struct BindTypeHelper {
682 static constexpr size_t num_bounds = sizeof...(BoundArgs);
683 using FunctorTraits = MakeFunctorTraits<Functor>;
684
685 // Example:
686 // When Functor is `double (Foo::*)(int, const std::string&)`, and BoundArgs
687 // is a template pack of `Foo*` and `int16_t`:
688 // - RunType is `double(Foo*, int, const std::string&)`,
689 // - ReturnType is `double`,
690 // - RunParamsList is `TypeList<Foo*, int, const std::string&>`,
691 // - BoundParamsList is `TypeList<Foo*, int>`,
692 // - UnboundParamsList is `TypeList<const std::string&>`,
693 // - BoundArgsList is `TypeList<Foo*, int16_t>`,
694 // - UnboundRunType is `double(const std::string&)`.
695 using RunType = typename FunctorTraits::RunType;
tzikcaf1d84b2016-06-28 12:22:21696 using ReturnType = ExtractReturnType<RunType>;
tzikae4202e2017-07-31 10:41:54697
698 using RunParamsList = ExtractArgs<RunType>;
699 using BoundParamsList = TakeTypeListItem<num_bounds, RunParamsList>;
700 using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
701
702 using BoundArgsList = TypeList<BoundArgs...>;
703
704 using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
tzikcaf1d84b2016-06-28 12:22:21705};
tzikae4202e2017-07-31 10:41:54706
tzikc1db72652016-07-08 09:42:38707template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53708std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
709 const Functor& functor) {
tzikc1db72652016-07-08 09:42:38710 return !functor;
711}
712
713template <typename Functor>
Jeremy Roman35a317432017-08-16 22:20:53714std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
715 const Functor&) {
tzikc1db72652016-07-08 09:42:38716 return false;
717}
tzikcaf1d84b2016-06-28 12:22:21718
tzik9697d49e2018-08-02 13:35:19719// Used by QueryCancellationTraits below.
tzik6c92eab2016-11-25 15:56:36720template <typename Functor, typename BoundArgsTuple, size_t... indices>
tzik9697d49e2018-08-02 13:35:19721bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
722 const Functor& functor,
723 const BoundArgsTuple& bound_args,
724 std::index_sequence<indices...>) {
725 switch (mode) {
726 case BindStateBase::IS_CANCELLED:
727 return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
728 functor, std::get<indices>(bound_args)...);
729 case BindStateBase::MAYBE_VALID:
730 return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
731 functor, std::get<indices>(bound_args)...);
732 }
733 NOTREACHED();
tzik6c92eab2016-11-25 15:56:36734}
tzik59aa6bb12016-09-08 10:58:53735
tzik6c92eab2016-11-25 15:56:36736// Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
737// true if the callback |base| represents is canceled.
738template <typename BindStateType>
tzik9697d49e2018-08-02 13:35:19739bool QueryCancellationTraits(const BindStateBase* base,
740 BindStateBase::CancellationQueryMode mode) {
tzik6c92eab2016-11-25 15:56:36741 const BindStateType* storage = static_cast<const BindStateType*>(base);
742 static constexpr size_t num_bound_args =
743 std::tuple_size<decltype(storage->bound_args_)>::value;
tzik9697d49e2018-08-02 13:35:19744 return QueryCancellationTraitsImpl(
745 mode, storage->functor_, storage->bound_args_,
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:48746 std::make_index_sequence<num_bound_args>());
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:48747}
748
tzikefea4f52018-08-02 15:20:46749// The base case of BanUnconstructedRefCountedReceiver that checks nothing.
750template <typename Functor, typename Receiver, typename... Unused>
751std::enable_if_t<
752 !(MakeFunctorTraits<Functor>::is_method &&
753 std::is_pointer<std::decay_t<Receiver>>::value &&
754 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
755BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
756
757template <typename Functor>
758void BanUnconstructedRefCountedReceiver() {}
759
760// Asserts that Callback is not the first owner of a ref-counted receiver.
761template <typename Functor, typename Receiver, typename... Unused>
762std::enable_if_t<
763 MakeFunctorTraits<Functor>::is_method &&
764 std::is_pointer<std::decay_t<Receiver>>::value &&
765 IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
766BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
767 DCHECK(receiver);
768
769 // It's error prone to make the implicit first reference to ref-counted types.
770 // In the example below, base::BindOnce() makes the implicit first reference
771 // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
772 // enough, the newly created instance can be destroyed before |oo| makes
773 // another reference.
774 // Foo::Foo() {
775 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
776 // }
777 //
778 // scoped_refptr<Foo> oo = new Foo();
779 //
780 // Instead of doing like above, please consider adding a static constructor,
781 // and keep the first reference alive explicitly.
782 // // static
783 // scoped_refptr<Foo> Foo::Create() {
784 // auto foo = base::WrapRefCounted(new Foo());
785 // base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
786 // return foo;
787 // }
788 //
789 // Foo::Foo() {}
790 //
791 // scoped_refptr<Foo> oo = Foo::Create();
792 DCHECK(receiver->HasAtLeastOneRef())
kylechar2255ccc2019-09-11 21:47:23793 << "base::Bind{Once,Repeating}() refuses to create the first reference "
794 "to ref-counted objects. That typically happens around PostTask() in "
795 "their constructor, and such objects can be destroyed before `new` "
796 "returns if the task resolves fast enough.";
tzikefea4f52018-08-02 15:20:46797}
798
[email protected]7296f2762011-11-21 19:23:44799// BindState<>
800//
tzik99de02b2016-07-01 05:54:12801// This stores all the state passed into Bind().
802template <typename Functor, typename... BoundArgs>
803struct BindState final : BindStateBase {
tzik1fdcca32016-09-14 07:15:00804 using IsCancellable = std::integral_constant<
tzik6c92eab2016-11-25 15:56:36805 bool,
806 CallbackCancellationTraits<Functor,
807 std::tuple<BoundArgs...>>::is_cancellable>;
tzik1fdcca32016-09-14 07:15:00808
tzikbfe66122016-07-08 14:14:01809 template <typename ForwardFunctor, typename... ForwardBoundArgs>
tzikefea4f52018-08-02 15:20:46810 static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
811 ForwardFunctor&& functor,
812 ForwardBoundArgs&&... bound_args) {
813 // Ban ref counted receivers that were not yet fully constructed to avoid
814 // a common pattern of racy situation.
815 BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
816
817 // IsCancellable is std::false_type if
818 // CallbackCancellationTraits<>::IsCancelled returns always false.
819 // Otherwise, it's std::true_type.
820 return new BindState(IsCancellable{}, invoke_func,
821 std::forward<ForwardFunctor>(functor),
822 std::forward<ForwardBoundArgs>(bound_args)...);
823 }
tzik1fdcca32016-09-14 07:15:00824
825 Functor functor_;
826 std::tuple<BoundArgs...> bound_args_;
827
828 private:
829 template <typename ForwardFunctor, typename... ForwardBoundArgs>
830 explicit BindState(std::true_type,
831 BindStateBase::InvokeFuncStorage invoke_func,
832 ForwardFunctor&& functor,
833 ForwardBoundArgs&&... bound_args)
tzik6c92eab2016-11-25 15:56:36834 : BindStateBase(invoke_func,
835 &Destroy,
tzik9697d49e2018-08-02 13:35:19836 &QueryCancellationTraits<BindState>),
tzikff54a5b152016-08-31 11:50:41837 functor_(std::forward<ForwardFunctor>(functor)),
tzik99de02b2016-07-01 05:54:12838 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
tzikc1db72652016-07-08 09:42:38839 DCHECK(!IsNull(functor_));
tzik99de02b2016-07-01 05:54:12840 }
[email protected]7296f2762011-11-21 19:23:44841
tzik1fdcca32016-09-14 07:15:00842 template <typename ForwardFunctor, typename... ForwardBoundArgs>
843 explicit BindState(std::false_type,
844 BindStateBase::InvokeFuncStorage invoke_func,
845 ForwardFunctor&& functor,
846 ForwardBoundArgs&&... bound_args)
847 : BindStateBase(invoke_func, &Destroy),
848 functor_(std::forward<ForwardFunctor>(functor)),
849 bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
850 DCHECK(!IsNull(functor_));
851 }
dmichael7d09007e2014-12-18 22:30:11852
Chris Watkins091d6292017-12-13 04:25:58853 ~BindState() = default;
taptede7e804c2015-05-14 08:03:32854
tzik30e0c312016-09-21 08:06:54855 static void Destroy(const BindStateBase* self) {
856 delete static_cast<const BindState*>(self);
taptede7e804c2015-05-14 08:03:32857 }
[email protected]fccef1552011-11-28 22:13:54858};
859
tzik99de02b2016-07-01 05:54:12860// Used to implement MakeBindStateType.
861template <bool is_method, typename Functor, typename... BoundArgs>
862struct MakeBindStateTypeImpl;
863
864template <typename Functor, typename... BoundArgs>
865struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
Jeremy Roman35a317432017-08-16 22:20:53866 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
tzik99de02b2016-07-01 05:54:12867 "A parameter is a refcounted type and needs scoped_refptr.");
Jeremy Roman35a317432017-08-16 22:20:53868 using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
tzik99de02b2016-07-01 05:54:12869};
870
871template <typename Functor>
872struct MakeBindStateTypeImpl<true, Functor> {
Jeremy Roman35a317432017-08-16 22:20:53873 using Type = BindState<std::decay_t<Functor>>;
tzik99de02b2016-07-01 05:54:12874};
875
876template <typename Functor, typename Receiver, typename... BoundArgs>
877struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
tzik99de02b2016-07-01 05:54:12878 private:
Jeremy Roman35a317432017-08-16 22:20:53879 using DecayedReceiver = std::decay_t<Receiver>;
tzik99de02b2016-07-01 05:54:12880
tzik4625ac612018-02-28 09:43:55881 static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
882 "First bound argument to a method cannot be an array.");
883 static_assert(
884 !std::is_pointer<DecayedReceiver>::value ||
885 IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
886 "Receivers may not be raw pointers. If using a raw pointer here is safe"
887 " and has no lifetime concerns, use base::Unretained() and document why"
888 " it's safe.");
889 static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
890 "A parameter is a refcounted type and needs scoped_refptr.");
891
tzik99de02b2016-07-01 05:54:12892 public:
893 using Type = BindState<
Jeremy Roman35a317432017-08-16 22:20:53894 std::decay_t<Functor>,
895 std::conditional_t<std::is_pointer<DecayedReceiver>::value,
896 scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
897 DecayedReceiver>,
898 std::decay_t<BoundArgs>...>;
tzik99de02b2016-07-01 05:54:12899};
900
901template <typename Functor, typename... BoundArgs>
tzikae4202e2017-07-31 10:41:54902using MakeBindStateType =
903 typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
904 Functor,
905 BoundArgs...>::Type;
tzik99de02b2016-07-01 05:54:12906
[email protected]b38d3572011-02-15 01:27:38907} // namespace internal
tzikcaf1d84b2016-06-28 12:22:21908
Peter Kastinga85265e32018-02-15 08:30:23909// An injection point to control |this| pointer behavior on a method invocation.
910// If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
911// method, base::Bind cancels the method invocation if the receiver is tested as
912// false.
913// E.g. Foo::bar() is not called:
914// struct Foo : base::SupportsWeakPtr<Foo> {
915// void bar() {}
916// };
917//
918// WeakPtr<Foo> oo = nullptr;
kylechar2255ccc2019-09-11 21:47:23919// base::BindOnce(&Foo::bar, oo).Run();
Peter Kastinga85265e32018-02-15 08:30:23920template <typename T>
921struct IsWeakReceiver : std::false_type {};
922
923template <typename T>
jdoerriec79c2fa22019-02-26 12:35:03924struct IsWeakReceiver<std::reference_wrapper<T>> : IsWeakReceiver<T> {};
Peter Kastinga85265e32018-02-15 08:30:23925
926template <typename T>
927struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
928
929// An injection point to control how bound objects passed to the target
930// function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
931// before the target function is invoked.
932template <typename>
933struct BindUnwrapTraits {
934 template <typename T>
935 static T&& Unwrap(T&& o) {
936 return std::forward<T>(o);
937 }
938};
939
940template <typename T>
941struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
942 static T* Unwrap(const internal::UnretainedWrapper<T>& o) { return o.get(); }
943};
944
945template <typename T>
jdoerriec79c2fa22019-02-26 12:35:03946struct BindUnwrapTraits<std::reference_wrapper<T>> {
947 static T& Unwrap(std::reference_wrapper<T> o) { return o.get(); }
Peter Kastinga85265e32018-02-15 08:30:23948};
949
950template <typename T>
951struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
952 static T* Unwrap(const internal::RetainedRefWrapper<T>& o) { return o.get(); }
953};
954
955template <typename T>
956struct BindUnwrapTraits<internal::OwnedWrapper<T>> {
957 static T* Unwrap(const internal::OwnedWrapper<T>& o) { return o.get(); }
958};
959
960template <typename T>
961struct BindUnwrapTraits<internal::PassedWrapper<T>> {
962 static T Unwrap(const internal::PassedWrapper<T>& o) { return o.Take(); }
963};
964
tzikc44f8102018-07-24 09:49:19965#if defined(OS_WIN)
966template <typename T>
967struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
968 static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
969};
970#endif
971
Peter Kastinga85265e32018-02-15 08:30:23972// CallbackCancellationTraits allows customization of Callback's cancellation
973// semantics. By default, callbacks are not cancellable. A specialization should
974// set is_cancellable = true and implement an IsCancelled() that returns if the
975// callback should be cancelled.
976template <typename Functor, typename BoundArgsTuple, typename SFINAE>
977struct CallbackCancellationTraits {
978 static constexpr bool is_cancellable = false;
979};
980
981// Specialization for method bound to weak pointer receiver.
982template <typename Functor, typename... BoundArgs>
983struct CallbackCancellationTraits<
984 Functor,
985 std::tuple<BoundArgs...>,
986 std::enable_if_t<
987 internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
988 BoundArgs...>::value>> {
989 static constexpr bool is_cancellable = true;
990
991 template <typename Receiver, typename... Args>
992 static bool IsCancelled(const Functor&,
993 const Receiver& receiver,
994 const Args&...) {
995 return !receiver;
996 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:48997
998 template <typename Receiver, typename... Args>
999 static bool MaybeValid(const Functor&,
1000 const Receiver& receiver,
1001 const Args&...) {
1002 return receiver.MaybeValid();
1003 }
Peter Kastinga85265e32018-02-15 08:30:231004};
1005
1006// Specialization for a nested bind.
1007template <typename Signature, typename... BoundArgs>
1008struct CallbackCancellationTraits<OnceCallback<Signature>,
1009 std::tuple<BoundArgs...>> {
1010 static constexpr bool is_cancellable = true;
1011
1012 template <typename Functor>
1013 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1014 return functor.IsCancelled();
1015 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:481016
1017 template <typename Functor>
1018 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1019 return functor.MaybeValid();
1020 }
Peter Kastinga85265e32018-02-15 08:30:231021};
1022
1023template <typename Signature, typename... BoundArgs>
1024struct CallbackCancellationTraits<RepeatingCallback<Signature>,
1025 std::tuple<BoundArgs...>> {
1026 static constexpr bool is_cancellable = true;
1027
1028 template <typename Functor>
1029 static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
1030 return functor.IsCancelled();
1031 }
Nicolas Ouellet-payeur40f8e9a2018-07-30 16:26:481032
1033 template <typename Functor>
1034 static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
1035 return functor.MaybeValid();
1036 }
Peter Kastinga85265e32018-02-15 08:30:231037};
1038
tzikcaf1d84b2016-06-28 12:22:211039// Returns a RunType of bound functor.
1040// E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
1041template <typename Functor, typename... BoundArgs>
1042using MakeUnboundRunType =
tzikae4202e2017-07-31 10:41:541043 typename internal::BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
tzikcaf1d84b2016-06-28 12:22:211044
[email protected]b38d3572011-02-15 01:27:381045} // namespace base
1046
1047#endif // BASE_BIND_INTERNAL_H_