blob: 66d5d82dd096f67ed6843c3aae2501dbbb3e807b [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_H_
6#define BASE_BIND_H_
[email protected]b38d3572011-02-15 01:27:387
Jeremy Roman84956fa2017-08-16 15:55:208#include <utility>
9
[email protected]b38d3572011-02-15 01:27:3810#include "base/bind_internal.h"
Sylvain Defresneec3270c2018-05-31 17:19:1511#include "base/compiler_specific.h"
12#include "build/build_config.h"
13
14#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
15#include "base/mac/scoped_block.h"
16#endif
[email protected]b38d3572011-02-15 01:27:3817
[email protected]24292642012-07-12 20:06:4018// -----------------------------------------------------------------------------
19// Usage documentation
20// -----------------------------------------------------------------------------
[email protected]b38d3572011-02-15 01:27:3821//
Daniel Chengb9d99f52018-02-19 22:21:5122// Overview:
23// base::BindOnce() and base::BindRepeating() are helpers for creating
24// base::OnceCallback and base::RepeatingCallback objects respectively.
[email protected]24292642012-07-12 20:06:4025//
Daniel Chengb9d99f52018-02-19 22:21:5126// For a runnable object of n-arity, the base::Bind*() family allows partial
27// application of the first m arguments. The remaining n - m arguments must be
28// passed when invoking the callback with Run().
29//
30// // The first argument is bound at callback creation; the remaining
31// // two must be passed when calling Run() on the callback object.
32// base::OnceCallback<void(int, long)> cb = base::BindOnce(
33// [](short x, int y, long z) { return x * y * z; }, 42);
34//
35// When binding to a method, the receiver object must also be specified at
36// callback creation time. When Run() is invoked, the method will be invoked on
37// the specified receiver object.
38//
39// class C : public base::RefCounted<C> { void F(); };
40// auto instance = base::MakeRefCounted<C>();
41// auto cb = base::BindOnce(&C::F, instance);
42// cb.Run(); // Identical to instance->F()
43//
44// base::Bind is currently a type alias for base::BindRepeating(). In the
45// future, we expect to flip this to default to base::BindOnce().
46//
47// See //docs/callback.md for the full documentation.
[email protected]24292642012-07-12 20:06:4048//
49// -----------------------------------------------------------------------------
50// Implementation notes
51// -----------------------------------------------------------------------------
52//
53// If you're reading the implementation, before proceeding further, you should
54// read the top comment of base/bind_internal.h for a definition of common
55// terms and concepts.
[email protected]b38d3572011-02-15 01:27:3856
57namespace base {
58
tzikae4202e2017-07-31 10:41:5459namespace internal {
60
61// IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
62template <typename T>
63struct IsOnceCallback : std::false_type {};
64
65template <typename Signature>
66struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
67
Daniel Chenga09cb602017-08-30 13:46:1968// Helper to assert that parameter |i| of type |Arg| can be bound, which means:
69// - |Arg| can be retained internally as |Storage|.
70// - |Arg| can be forwarded as |Unwrapped| to |Param|.
71template <size_t i,
72 typename Arg,
73 typename Storage,
74 typename Unwrapped,
75 typename Param>
tzikae4202e2017-07-31 10:41:5476struct AssertConstructible {
Daniel Chenga09cb602017-08-30 13:46:1977 private:
78 static constexpr bool param_is_forwardable =
79 std::is_constructible<Param, Unwrapped>::value;
80 // Unlike the check for binding into storage below, the check for
81 // forwardability drops the const qualifier for repeating callbacks. This is
82 // to try to catch instances where std::move()--which forwards as a const
83 // reference with repeating callbacks--is used instead of base::Passed().
84 static_assert(
85 param_is_forwardable ||
86 !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
87 "Bound argument |i| is move-only but will be forwarded by copy. "
88 "Ensure |Arg| is bound using base::Passed(), not std::move().");
89 static_assert(
90 param_is_forwardable,
91 "Bound argument |i| of type |Arg| cannot be forwarded as "
92 "|Unwrapped| to the bound functor, which declares it as |Param|.");
93
94 static constexpr bool arg_is_storable =
95 std::is_constructible<Storage, Arg>::value;
96 static_assert(arg_is_storable ||
97 !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
98 "Bound argument |i| is move-only but will be bound by copy. "
99 "Ensure |Arg| is mutable and bound using std::move().");
100 static_assert(arg_is_storable,
101 "Bound argument |i| of type |Arg| cannot be converted and "
102 "bound as |Storage|.");
tzikae4202e2017-07-31 10:41:54103};
104
105// Takes three same-length TypeLists, and applies AssertConstructible for each
106// triples.
107template <typename Index,
Daniel Chenga09cb602017-08-30 13:46:19108 typename Args,
tzikae4202e2017-07-31 10:41:54109 typename UnwrappedTypeList,
110 typename ParamsList>
111struct AssertBindArgsValidity;
112
113template <size_t... Ns,
114 typename... Args,
115 typename... Unwrapped,
116 typename... Params>
Jeremy Roman84956fa2017-08-16 15:55:20117struct AssertBindArgsValidity<std::index_sequence<Ns...>,
tzikae4202e2017-07-31 10:41:54118 TypeList<Args...>,
119 TypeList<Unwrapped...>,
120 TypeList<Params...>>
Daniel Chenga09cb602017-08-30 13:46:19121 : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
tzikae4202e2017-07-31 10:41:54122 static constexpr bool ok = true;
123};
124
125// The implementation of TransformToUnwrappedType below.
tzikd4bb5b7d2017-08-28 19:08:52126template <bool is_once, typename T>
tzikae4202e2017-07-31 10:41:54127struct TransformToUnwrappedTypeImpl;
128
129template <typename T>
tzikd4bb5b7d2017-08-28 19:08:52130struct TransformToUnwrappedTypeImpl<true, T> {
Jeremy Roman35a317432017-08-16 22:20:53131 using StoredType = std::decay_t<T>;
tzikae4202e2017-07-31 10:41:54132 using ForwardType = StoredType&&;
133 using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
134};
135
136template <typename T>
tzikd4bb5b7d2017-08-28 19:08:52137struct TransformToUnwrappedTypeImpl<false, T> {
Jeremy Roman35a317432017-08-16 22:20:53138 using StoredType = std::decay_t<T>;
tzikae4202e2017-07-31 10:41:54139 using ForwardType = const StoredType&;
140 using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
141};
142
143// Transform |T| into `Unwrapped` type, which is passed to the target function.
144// Example:
tzikd4bb5b7d2017-08-28 19:08:52145// In is_once == true case,
tzikae4202e2017-07-31 10:41:54146// `int&&` -> `int&&`,
147// `const int&` -> `int&&`,
148// `OwnedWrapper<int>&` -> `int*&&`.
tzikd4bb5b7d2017-08-28 19:08:52149// In is_once == false case,
tzikae4202e2017-07-31 10:41:54150// `int&&` -> `const int&`,
151// `const int&` -> `const int&`,
152// `OwnedWrapper<int>&` -> `int* const &`.
tzikd4bb5b7d2017-08-28 19:08:52153template <bool is_once, typename T>
tzikae4202e2017-07-31 10:41:54154using TransformToUnwrappedType =
tzikd4bb5b7d2017-08-28 19:08:52155 typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
tzikae4202e2017-07-31 10:41:54156
157// Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
158// If |is_method| is true, tries to dereference the first argument to support
159// smart pointers.
tzikd4bb5b7d2017-08-28 19:08:52160template <bool is_once, bool is_method, typename... Args>
tzikae4202e2017-07-31 10:41:54161struct MakeUnwrappedTypeListImpl {
tzikd4bb5b7d2017-08-28 19:08:52162 using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
tzikae4202e2017-07-31 10:41:54163};
164
165// Performs special handling for this pointers.
166// Example:
167// int* -> int*,
168// std::unique_ptr<int> -> int*.
tzikd4bb5b7d2017-08-28 19:08:52169template <bool is_once, typename Receiver, typename... Args>
170struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
171 using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
tzikae4202e2017-07-31 10:41:54172 using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
tzikd4bb5b7d2017-08-28 19:08:52173 TransformToUnwrappedType<is_once, Args>...>;
tzikae4202e2017-07-31 10:41:54174};
175
tzikd4bb5b7d2017-08-28 19:08:52176template <bool is_once, bool is_method, typename... Args>
tzikae4202e2017-07-31 10:41:54177using MakeUnwrappedTypeList =
tzikd4bb5b7d2017-08-28 19:08:52178 typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
tzikae4202e2017-07-31 10:41:54179
180} // namespace internal
181
tzik27d1e312016-09-13 05:28:59182// Bind as OnceCallback.
tzik401dd3672014-11-26 07:54:58183template <typename Functor, typename... Args>
tzik27d1e312016-09-13 05:28:59184inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
185BindOnce(Functor&& functor, Args&&... args) {
Jeremy Roman35a317432017-08-16 22:20:53186 static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
187 (std::is_rvalue_reference<Functor&&>() &&
188 !std::is_const<std::remove_reference_t<Functor>>()),
189 "BindOnce requires non-const rvalue for OnceCallback binding."
190 " I.e.: base::BindOnce(std::move(callback)).");
tzikae4202e2017-07-31 10:41:54191
192 // This block checks if each |args| matches to the corresponding params of the
193 // target function. This check does not affect the behavior of Bind, but its
194 // error message should be more readable.
195 using Helper = internal::BindTypeHelper<Functor, Args...>;
196 using FunctorTraits = typename Helper::FunctorTraits;
197 using BoundArgsList = typename Helper::BoundArgsList;
198 using UnwrappedArgsList =
tzikd4bb5b7d2017-08-28 19:08:52199 internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method,
200 Args&&...>;
tzikae4202e2017-07-31 10:41:54201 using BoundParamsList = typename Helper::BoundParamsList;
Jeremy Roman84956fa2017-08-16 15:55:20202 static_assert(internal::AssertBindArgsValidity<
203 std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
204 UnwrappedArgsList, BoundParamsList>::ok,
205 "The bound args need to be convertible to the target params.");
tzikae4202e2017-07-31 10:41:54206
tzik99de02b2016-07-01 05:54:12207 using BindState = internal::MakeBindStateType<Functor, Args...>;
tzikcaf1d84b2016-06-28 12:22:21208 using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
tzikcaf1d84b2016-06-28 12:22:21209 using Invoker = internal::Invoker<BindState, UnboundRunType>;
tzik27d1e312016-09-13 05:28:59210 using CallbackType = OnceCallback<UnboundRunType>;
211
212 // Store the invoke func into PolymorphicInvoke before casting it to
213 // InvokeFuncStorage, so that we can ensure its type matches to
214 // PolymorphicInvoke, to which CallbackType will cast back.
215 using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
216 PolymorphicInvoke invoke_func = &Invoker::RunOnce;
217
218 using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
219 return CallbackType(new BindState(
220 reinterpret_cast<InvokeFuncStorage>(invoke_func),
221 std::forward<Functor>(functor),
222 std::forward<Args>(args)...));
223}
224
225// Bind as RepeatingCallback.
226template <typename Functor, typename... Args>
227inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
228BindRepeating(Functor&& functor, Args&&... args) {
tzikae4202e2017-07-31 10:41:54229 static_assert(
Jeremy Roman35a317432017-08-16 22:20:53230 !internal::IsOnceCallback<std::decay_t<Functor>>(),
tzikae4202e2017-07-31 10:41:54231 "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
232
233 // This block checks if each |args| matches to the corresponding params of the
234 // target function. This check does not affect the behavior of Bind, but its
235 // error message should be more readable.
236 using Helper = internal::BindTypeHelper<Functor, Args...>;
237 using FunctorTraits = typename Helper::FunctorTraits;
238 using BoundArgsList = typename Helper::BoundArgsList;
239 using UnwrappedArgsList =
tzikd4bb5b7d2017-08-28 19:08:52240 internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method,
241 Args&&...>;
tzikae4202e2017-07-31 10:41:54242 using BoundParamsList = typename Helper::BoundParamsList;
Jeremy Roman84956fa2017-08-16 15:55:20243 static_assert(internal::AssertBindArgsValidity<
244 std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
245 UnwrappedArgsList, BoundParamsList>::ok,
246 "The bound args need to be convertible to the target params.");
tzikae4202e2017-07-31 10:41:54247
tzik27d1e312016-09-13 05:28:59248 using BindState = internal::MakeBindStateType<Functor, Args...>;
249 using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
250 using Invoker = internal::Invoker<BindState, UnboundRunType>;
251 using CallbackType = RepeatingCallback<UnboundRunType>;
tzik1886c272016-09-08 05:45:38252
253 // Store the invoke func into PolymorphicInvoke before casting it to
254 // InvokeFuncStorage, so that we can ensure its type matches to
255 // PolymorphicInvoke, to which CallbackType will cast back.
256 using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
257 PolymorphicInvoke invoke_func = &Invoker::Run;
258
259 using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
260 return CallbackType(new BindState(
261 reinterpret_cast<InvokeFuncStorage>(invoke_func),
262 std::forward<Functor>(functor),
263 std::forward<Args>(args)...));
[email protected]fccef1552011-11-28 22:13:54264}
265
tzik27d1e312016-09-13 05:28:59266// Unannotated Bind.
267// TODO(tzik): Deprecate this and migrate to OnceCallback and
268// RepeatingCallback, once they get ready.
269template <typename Functor, typename... Args>
270inline Callback<MakeUnboundRunType<Functor, Args...>>
271Bind(Functor&& functor, Args&&... args) {
Yuta Kitamurad6c13d8e2017-12-01 06:09:41272 return base::BindRepeating(std::forward<Functor>(functor),
273 std::forward<Args>(args)...);
tzik27d1e312016-09-13 05:28:59274}
275
tzikc20ed0b2017-08-18 22:59:55276// Special cases for binding to a base::Callback without extra bound arguments.
277template <typename Signature>
278OnceCallback<Signature> BindOnce(OnceCallback<Signature> closure) {
279 return closure;
280}
281
282template <typename Signature>
283RepeatingCallback<Signature> BindRepeating(
284 RepeatingCallback<Signature> closure) {
285 return closure;
286}
287
288template <typename Signature>
289Callback<Signature> Bind(Callback<Signature> closure) {
290 return closure;
291}
292
Peter Kastinga85265e32018-02-15 08:30:23293// Unretained() allows Bind() to bind a non-refcounted class, and to disable
294// refcounting on arguments that are refcounted objects.
295//
296// EXAMPLE OF Unretained():
297//
298// class Foo {
299// public:
300// void func() { cout << "Foo:f" << endl; }
301// };
302//
303// // In some function somewhere.
304// Foo foo;
305// Closure foo_callback =
306// Bind(&Foo::func, Unretained(&foo));
307// foo_callback.Run(); // Prints "Foo:f".
308//
309// Without the Unretained() wrapper on |&foo|, the above call would fail
310// to compile because Foo does not support the AddRef() and Release() methods.
311template <typename T>
312static inline internal::UnretainedWrapper<T> Unretained(T* o) {
313 return internal::UnretainedWrapper<T>(o);
314}
315
316// RetainedRef() accepts a ref counted object and retains a reference to it.
317// When the callback is called, the object is passed as a raw pointer.
318//
319// EXAMPLE OF RetainedRef():
320//
321// void foo(RefCountedBytes* bytes) {}
322//
323// scoped_refptr<RefCountedBytes> bytes = ...;
324// Closure callback = Bind(&foo, base::RetainedRef(bytes));
325// callback.Run();
326//
327// Without RetainedRef, the scoped_refptr would try to implicitly convert to
328// a raw pointer and fail compilation:
329//
330// Closure callback = Bind(&foo, bytes); // ERROR!
331template <typename T>
332static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
333 return internal::RetainedRefWrapper<T>(o);
334}
335template <typename T>
336static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
337 return internal::RetainedRefWrapper<T>(std::move(o));
338}
339
340// ConstRef() allows binding a constant reference to an argument rather
341// than a copy.
342//
343// EXAMPLE OF ConstRef():
344//
345// void foo(int arg) { cout << arg << endl }
346//
347// int n = 1;
348// Closure no_ref = Bind(&foo, n);
349// Closure has_ref = Bind(&foo, ConstRef(n));
350//
351// no_ref.Run(); // Prints "1"
352// has_ref.Run(); // Prints "1"
353//
354// n = 2;
355// no_ref.Run(); // Prints "1"
356// has_ref.Run(); // Prints "2"
357//
358// Note that because ConstRef() takes a reference on |n|, |n| must outlive all
359// its bound callbacks.
360template <typename T>
361static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
362 return internal::ConstRefWrapper<T>(o);
363}
364
365// Owned() transfers ownership of an object to the Callback resulting from
366// bind; the object will be deleted when the Callback is deleted.
367//
368// EXAMPLE OF Owned():
369//
370// void foo(int* arg) { cout << *arg << endl }
371//
372// int* pn = new int(1);
373// Closure foo_callback = Bind(&foo, Owned(pn));
374//
375// foo_callback.Run(); // Prints "1"
376// foo_callback.Run(); // Prints "1"
377// *n = 2;
378// foo_callback.Run(); // Prints "2"
379//
380// foo_callback.Reset(); // |pn| is deleted. Also will happen when
381// // |foo_callback| goes out of scope.
382//
383// Without Owned(), someone would have to know to delete |pn| when the last
384// reference to the Callback is deleted.
385template <typename T>
386static inline internal::OwnedWrapper<T> Owned(T* o) {
387 return internal::OwnedWrapper<T>(o);
388}
389
390// Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
391// through a Callback. Logically, this signifies a destructive transfer of
392// the state of the argument into the target function. Invoking
393// Callback::Run() twice on a Callback that was created with a Passed()
394// argument will CHECK() because the first invocation would have already
395// transferred ownership to the target function.
396//
Max Morinb51cf512018-02-19 12:49:49397// Note that Passed() is not necessary with BindOnce(), as std::move() does the
398// same thing. Avoid Passed() in favor of std::move() with BindOnce().
399//
Peter Kastinga85265e32018-02-15 08:30:23400// EXAMPLE OF Passed():
401//
402// void TakesOwnership(std::unique_ptr<Foo> arg) { }
Max Morinb51cf512018-02-19 12:49:49403// std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
Peter Kastinga85265e32018-02-15 08:30:23404// }
405//
Max Morinb51cf512018-02-19 12:49:49406// auto f = std::make_unique<Foo>();
Peter Kastinga85265e32018-02-15 08:30:23407//
408// // |cb| is given ownership of Foo(). |f| is now NULL.
409// // You can use std::move(f) in place of &f, but it's more verbose.
410// Closure cb = Bind(&TakesOwnership, Passed(&f));
411//
412// // Run was never called so |cb| still owns Foo() and deletes
413// // it on Reset().
414// cb.Reset();
415//
416// // |cb| is given a new Foo created by CreateFoo().
417// cb = Bind(&TakesOwnership, Passed(CreateFoo()));
418//
419// // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
420// // no longer owns Foo() and, if reset, would not delete Foo().
421// cb.Run(); // Foo() is now transferred to |arg| and deleted.
422// cb.Run(); // This CHECK()s since Foo() already been used once.
423//
Peter Kastinga85265e32018-02-15 08:30:23424// We offer 2 syntaxes for calling Passed(). The first takes an rvalue and
425// is best suited for use with the return value of a function or other temporary
426// rvalues. The second takes a pointer to the scoper and is just syntactic sugar
427// to avoid having to write Passed(std::move(scoper)).
428//
429// Both versions of Passed() prevent T from being an lvalue reference. The first
430// via use of enable_if, and the second takes a T* which will not bind to T&.
431template <typename T,
432 std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
433static inline internal::PassedWrapper<T> Passed(T&& scoper) {
434 return internal::PassedWrapper<T>(std::move(scoper));
435}
436template <typename T>
437static inline internal::PassedWrapper<T> Passed(T* scoper) {
438 return internal::PassedWrapper<T>(std::move(*scoper));
439}
440
441// IgnoreResult() is used to adapt a function or Callback with a return type to
442// one with a void return. This is most useful if you have a function with,
443// say, a pesky ignorable bool return that you want to use with PostTask or
444// something else that expect a Callback with a void return.
445//
446// EXAMPLE OF IgnoreResult():
447//
448// int DoSomething(int arg) { cout << arg << endl; }
449//
450// // Assign to a Callback with a void return type.
451// Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
452// cb->Run(1); // Prints "1".
453//
454// // Prints "1" on |ml|.
455// ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
456template <typename T>
457static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
458 return internal::IgnoreResultHelper<T>(std::move(data));
459}
460
Sylvain Defresneec3270c2018-05-31 17:19:15461#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
462
463// RetainBlock() is used to adapt an Objective-C block when Automated Reference
464// Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
465// BindOnce and BindRepeating already support blocks then.
466//
467// EXAMPLE OF RetainBlock():
468//
469// // Wrap the block and bind it to a callback.
470// Callback<void(int)> cb = Bind(RetainBlock(^(int n) { NSLog(@"%d", n); }));
471// cb.Run(1); // Logs "1".
472template <typename R, typename... Args>
473base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
474 return base::mac::ScopedBlock<R (^)(Args...)>(block,
475 base::scoped_policy::RETAIN);
476}
477
478#endif // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
479
[email protected]b38d3572011-02-15 01:27:38480} // namespace base
481
482#endif // BASE_BIND_H_