bind.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_BIND_H_
  5. #define BASE_BIND_H_
  6. #include <functional>
  7. #include <memory>
  8. #include <type_traits>
  9. #include <utility>
  10. #include "base/bind_internal.h"
  11. #include "base/compiler_specific.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "build/build_config.h"
  14. #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
  15. #include "base/mac/scoped_block.h"
  16. #endif
  17. // -----------------------------------------------------------------------------
  18. // Usage documentation
  19. // -----------------------------------------------------------------------------
  20. //
  21. // Overview:
  22. // base::BindOnce() and base::BindRepeating() are helpers for creating
  23. // base::OnceCallback and base::RepeatingCallback objects respectively.
  24. //
  25. // For a runnable object of n-arity, the base::Bind*() family allows partial
  26. // application of the first m arguments. The remaining n - m arguments must be
  27. // passed when invoking the callback with Run().
  28. //
  29. // // The first argument is bound at callback creation; the remaining
  30. // // two must be passed when calling Run() on the callback object.
  31. // base::OnceCallback<long(int, long)> cb = base::BindOnce(
  32. // [](short x, int y, long z) { return x * y * z; }, 42);
  33. //
  34. // When binding to a method, the receiver object must also be specified at
  35. // callback creation time. When Run() is invoked, the method will be invoked on
  36. // the specified receiver object.
  37. //
  38. // class C : public base::RefCounted<C> { void F(); };
  39. // auto instance = base::MakeRefCounted<C>();
  40. // auto cb = base::BindOnce(&C::F, instance);
  41. // std::move(cb).Run(); // Identical to instance->F()
  42. //
  43. // See //docs/callback.md for the full documentation.
  44. //
  45. // -----------------------------------------------------------------------------
  46. // Implementation notes
  47. // -----------------------------------------------------------------------------
  48. //
  49. // If you're reading the implementation, before proceeding further, you should
  50. // read the top comment of base/bind_internal.h for a definition of common
  51. // terms and concepts.
  52. namespace base {
  53. // Bind as OnceCallback.
  54. template <typename Functor, typename... Args>
  55. inline OnceCallback<internal::MakeUnboundRunType<Functor, Args...>> BindOnce(
  56. Functor&& functor,
  57. Args&&... args) {
  58. static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
  59. (std::is_rvalue_reference<Functor&&>() &&
  60. !std::is_const<std::remove_reference_t<Functor>>()),
  61. "BindOnce requires non-const rvalue for OnceCallback binding."
  62. " I.e.: base::BindOnce(std::move(callback)).");
  63. static_assert(
  64. std::conjunction<
  65. internal::AssertBindArgIsNotBasePassed<std::decay_t<Args>>...>::value,
  66. "Use std::move() instead of base::Passed() with base::BindOnce()");
  67. return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor),
  68. std::forward<Args>(args)...);
  69. }
  70. // Bind as RepeatingCallback.
  71. template <typename Functor, typename... Args>
  72. inline RepeatingCallback<internal::MakeUnboundRunType<Functor, Args...>>
  73. BindRepeating(Functor&& functor, Args&&... args) {
  74. static_assert(
  75. !internal::IsOnceCallback<std::decay_t<Functor>>(),
  76. "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
  77. return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor),
  78. std::forward<Args>(args)...);
  79. }
  80. // Overloads to allow nicer compile errors when attempting to pass the address
  81. // an overloaded function to `BindOnce()` or `BindRepeating()`. Otherwise, clang
  82. // provides only the error message "no matching function [...] candidate
  83. // template ignored: couldn't infer template argument 'Functor'", with no
  84. // reference to the fact that `&` is being used on an overloaded function.
  85. //
  86. // These overloads to provide better error messages will never be selected
  87. // unless template type deduction fails because of how overload resolution
  88. // works; per [over.ics.rank/2.2]:
  89. //
  90. // When comparing the basic forms of implicit conversion sequences (as defined
  91. // in [over.best.ics])
  92. // - a standard conversion sequence is a better conversion sequence than a
  93. // user-defined conversion sequence or an ellipsis conversion sequence, and
  94. // - a user-defined conversion sequence is a better conversion sequence than
  95. // an ellipsis conversion sequence.
  96. //
  97. // So these overloads will only be selected as a last resort iff template type
  98. // deduction fails.
  99. //
  100. // These overloads also intentionally do not return `void`, as this prevents
  101. // clang from emitting spurious errors such as "variable has incomplete type
  102. // 'void'" when assigning the result of `BindOnce()`/`BindRepeating()` to a
  103. // variable with type `auto` or `decltype(auto)`.
  104. struct BindFailedCheckPreviousErrors {};
  105. BindFailedCheckPreviousErrors BindOnce(...);
  106. BindFailedCheckPreviousErrors BindRepeating(...);
  107. // Unretained() allows binding a non-refcounted class, and to disable
  108. // refcounting on arguments that are refcounted objects.
  109. //
  110. // EXAMPLE OF Unretained():
  111. //
  112. // class Foo {
  113. // public:
  114. // void func() { cout << "Foo:f" << endl; }
  115. // };
  116. //
  117. // // In some function somewhere.
  118. // Foo foo;
  119. // OnceClosure foo_callback =
  120. // BindOnce(&Foo::func, Unretained(&foo));
  121. // std::move(foo_callback).Run(); // Prints "Foo:f".
  122. //
  123. // Without the Unretained() wrapper on |&foo|, the above call would fail
  124. // to compile because Foo does not support the AddRef() and Release() methods.
  125. template <typename T>
  126. inline internal::UnretainedWrapper<T> Unretained(T* o) {
  127. return internal::UnretainedWrapper<T>(o);
  128. }
  129. template <typename T, typename I>
  130. inline internal::UnretainedWrapper<T> Unretained(const raw_ptr<T, I>& o) {
  131. return internal::UnretainedWrapper<T>(o);
  132. }
  133. template <typename T, typename I>
  134. inline internal::UnretainedWrapper<T> Unretained(raw_ptr<T, I>&& o) {
  135. return internal::UnretainedWrapper<T>(std::move(o));
  136. }
  137. template <typename T, typename I>
  138. inline auto Unretained(const raw_ref<T, I>& o) {
  139. return internal::UnretainedRefWrapper(o);
  140. }
  141. template <typename T, typename I>
  142. inline auto Unretained(raw_ref<T, I>&& o) {
  143. return internal::UnretainedRefWrapper(std::move(o));
  144. }
  145. // RetainedRef() accepts a ref counted object and retains a reference to it.
  146. // When the callback is called, the object is passed as a raw pointer.
  147. //
  148. // EXAMPLE OF RetainedRef():
  149. //
  150. // void foo(RefCountedBytes* bytes) {}
  151. //
  152. // scoped_refptr<RefCountedBytes> bytes = ...;
  153. // OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
  154. // std::move(callback).Run();
  155. //
  156. // Without RetainedRef, the scoped_refptr would try to implicitly convert to
  157. // a raw pointer and fail compilation:
  158. //
  159. // OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
  160. template <typename T>
  161. inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
  162. return internal::RetainedRefWrapper<T>(o);
  163. }
  164. template <typename T>
  165. inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
  166. return internal::RetainedRefWrapper<T>(std::move(o));
  167. }
  168. // Owned() transfers ownership of an object to the callback resulting from
  169. // bind; the object will be deleted when the callback is deleted.
  170. //
  171. // EXAMPLE OF Owned():
  172. //
  173. // void foo(int* arg) { cout << *arg << endl }
  174. //
  175. // int* pn = new int(1);
  176. // RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
  177. //
  178. // foo_callback.Run(); // Prints "1"
  179. // foo_callback.Run(); // Prints "1"
  180. // *pn = 2;
  181. // foo_callback.Run(); // Prints "2"
  182. //
  183. // foo_callback.Reset(); // |pn| is deleted. Also will happen when
  184. // // |foo_callback| goes out of scope.
  185. //
  186. // Without Owned(), someone would have to know to delete |pn| when the last
  187. // reference to the callback is deleted.
  188. template <typename T>
  189. inline internal::OwnedWrapper<T> Owned(T* o) {
  190. return internal::OwnedWrapper<T>(o);
  191. }
  192. template <typename T, typename Deleter>
  193. inline internal::OwnedWrapper<T, Deleter> Owned(
  194. std::unique_ptr<T, Deleter>&& ptr) {
  195. return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
  196. }
  197. // OwnedRef() stores an object in the callback resulting from
  198. // bind and passes a reference to the object to the bound function.
  199. //
  200. // EXAMPLE OF OwnedRef():
  201. //
  202. // void foo(int& arg) { cout << ++arg << endl }
  203. //
  204. // int counter = 0;
  205. // RepeatingClosure foo_callback = BindRepeating(&foo, OwnedRef(counter));
  206. //
  207. // foo_callback.Run(); // Prints "1"
  208. // foo_callback.Run(); // Prints "2"
  209. // foo_callback.Run(); // Prints "3"
  210. //
  211. // cout << counter; // Prints "0", OwnedRef creates a copy of counter.
  212. //
  213. // Supports OnceCallbacks as well, useful to pass placeholder arguments:
  214. //
  215. // void bar(int& ignore, const std::string& s) { cout << s << endl }
  216. //
  217. // OnceClosure bar_callback = BindOnce(&bar, OwnedRef(0), "Hello");
  218. //
  219. // std::move(bar_callback).Run(); // Prints "Hello"
  220. //
  221. // Without OwnedRef() it would not be possible to pass a mutable reference to an
  222. // object owned by the callback.
  223. template <typename T>
  224. internal::OwnedRefWrapper<std::decay_t<T>> OwnedRef(T&& t) {
  225. return internal::OwnedRefWrapper<std::decay_t<T>>(std::forward<T>(t));
  226. }
  227. // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
  228. // through a RepeatingCallback. Logically, this signifies a destructive transfer
  229. // of the state of the argument into the target function. Invoking
  230. // RepeatingCallback::Run() twice on a callback that was created with a Passed()
  231. // argument will CHECK() because the first invocation would have already
  232. // transferred ownership to the target function.
  233. //
  234. // Note that Passed() is not necessary with BindOnce(), as std::move() does the
  235. // same thing. Avoid Passed() in favor of std::move() with BindOnce().
  236. //
  237. // EXAMPLE OF Passed():
  238. //
  239. // void TakesOwnership(std::unique_ptr<Foo> arg) { }
  240. // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
  241. // }
  242. //
  243. // auto f = std::make_unique<Foo>();
  244. //
  245. // // |cb| is given ownership of Foo(). |f| is now NULL.
  246. // // You can use std::move(f) in place of &f, but it's more verbose.
  247. // RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
  248. //
  249. // // Run was never called so |cb| still owns Foo() and deletes
  250. // // it on Reset().
  251. // cb.Reset();
  252. //
  253. // // |cb| is given a new Foo created by CreateFoo().
  254. // cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
  255. //
  256. // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
  257. // // no longer owns Foo() and, if reset, would not delete Foo().
  258. // cb.Run(); // Foo() is now transferred to |arg| and deleted.
  259. // cb.Run(); // This CHECK()s since Foo() already been used once.
  260. //
  261. // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
  262. // best suited for use with the return value of a function or other temporary
  263. // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
  264. // to avoid having to write Passed(std::move(scoper)).
  265. //
  266. // Both versions of Passed() prevent T from being an lvalue reference. The first
  267. // via use of enable_if, and the second takes a T* which will not bind to T&.
  268. template <typename T,
  269. std::enable_if_t<!std::is_lvalue_reference_v<T>>* = nullptr>
  270. inline internal::PassedWrapper<T> Passed(T&& scoper) {
  271. return internal::PassedWrapper<T>(std::move(scoper));
  272. }
  273. template <typename T>
  274. inline internal::PassedWrapper<T> Passed(T* scoper) {
  275. return internal::PassedWrapper<T>(std::move(*scoper));
  276. }
  277. // IgnoreResult() is used to adapt a function or callback with a return type to
  278. // one with a void return. This is most useful if you have a function with,
  279. // say, a pesky ignorable bool return that you want to use with PostTask or
  280. // something else that expect a callback with a void return.
  281. //
  282. // EXAMPLE OF IgnoreResult():
  283. //
  284. // int DoSomething(int arg) { cout << arg << endl; }
  285. //
  286. // // Assign to a callback with a void return type.
  287. // OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
  288. // std::move(cb).Run(1); // Prints "1".
  289. //
  290. // // Prints "2" on |ml|.
  291. // ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
  292. template <typename T>
  293. inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
  294. return internal::IgnoreResultHelper<T>(std::move(data));
  295. }
  296. #if BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
  297. // RetainBlock() is used to adapt an Objective-C block when Automated Reference
  298. // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
  299. // BindOnce and BindRepeating already support blocks then.
  300. //
  301. // EXAMPLE OF RetainBlock():
  302. //
  303. // // Wrap the block and bind it to a callback.
  304. // OnceCallback<void(int)> cb =
  305. // BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); }));
  306. // std::move(cb).Run(1); // Logs "1".
  307. template <typename R, typename... Args>
  308. base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
  309. return base::mac::ScopedBlock<R (^)(Args...)>(block,
  310. base::scoped_policy::RETAIN);
  311. }
  312. #endif // BUILDFLAG(IS_APPLE) && !HAS_FEATURE(objc_arc)
  313. } // namespace base
  314. #endif // BASE_BIND_H_