bind.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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/template_util.h"
  13. #include "build/build_config.h"
  14. #if defined(OS_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. // base::Bind is currently a type alias for base::BindRepeating(). In the
  44. // future, we expect to flip this to default to base::BindOnce().
  45. //
  46. // See //docs/callback.md for the full documentation.
  47. //
  48. // -----------------------------------------------------------------------------
  49. // Implementation notes
  50. // -----------------------------------------------------------------------------
  51. //
  52. // If you're reading the implementation, before proceeding further, you should
  53. // read the top comment of base/bind_internal.h for a definition of common
  54. // terms and concepts.
  55. namespace base {
  56. namespace internal {
  57. // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
  58. template <typename T>
  59. struct IsOnceCallback : std::false_type {};
  60. template <typename Signature>
  61. struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
  62. // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
  63. // - |Arg| can be retained internally as |Storage|.
  64. // - |Arg| can be forwarded as |Unwrapped| to |Param|.
  65. template <size_t i,
  66. typename Arg,
  67. typename Storage,
  68. typename Unwrapped,
  69. typename Param>
  70. struct AssertConstructible {
  71. private:
  72. static constexpr bool param_is_forwardable =
  73. std::is_constructible<Param, Unwrapped>::value;
  74. // Unlike the check for binding into storage below, the check for
  75. // forwardability drops the const qualifier for repeating callbacks. This is
  76. // to try to catch instances where std::move()--which forwards as a const
  77. // reference with repeating callbacks--is used instead of base::Passed().
  78. static_assert(
  79. param_is_forwardable ||
  80. !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
  81. "Bound argument |i| is move-only but will be forwarded by copy. "
  82. "Ensure |Arg| is bound using base::Passed(), not std::move().");
  83. static_assert(
  84. param_is_forwardable,
  85. "Bound argument |i| of type |Arg| cannot be forwarded as "
  86. "|Unwrapped| to the bound functor, which declares it as |Param|.");
  87. static constexpr bool arg_is_storable =
  88. std::is_constructible<Storage, Arg>::value;
  89. static_assert(arg_is_storable ||
  90. !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
  91. "Bound argument |i| is move-only but will be bound by copy. "
  92. "Ensure |Arg| is mutable and bound using std::move().");
  93. static_assert(arg_is_storable,
  94. "Bound argument |i| of type |Arg| cannot be converted and "
  95. "bound as |Storage|.");
  96. };
  97. // Takes three same-length TypeLists, and applies AssertConstructible for each
  98. // triples.
  99. template <typename Index,
  100. typename Args,
  101. typename UnwrappedTypeList,
  102. typename ParamsList>
  103. struct AssertBindArgsValidity;
  104. template <size_t... Ns,
  105. typename... Args,
  106. typename... Unwrapped,
  107. typename... Params>
  108. struct AssertBindArgsValidity<std::index_sequence<Ns...>,
  109. TypeList<Args...>,
  110. TypeList<Unwrapped...>,
  111. TypeList<Params...>>
  112. : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
  113. static constexpr bool ok = true;
  114. };
  115. // The implementation of TransformToUnwrappedType below.
  116. template <bool is_once, typename T>
  117. struct TransformToUnwrappedTypeImpl;
  118. template <typename T>
  119. struct TransformToUnwrappedTypeImpl<true, T> {
  120. using StoredType = std::decay_t<T>;
  121. using ForwardType = StoredType&&;
  122. using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
  123. };
  124. template <typename T>
  125. struct TransformToUnwrappedTypeImpl<false, T> {
  126. using StoredType = std::decay_t<T>;
  127. using ForwardType = const StoredType&;
  128. using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
  129. };
  130. // Transform |T| into `Unwrapped` type, which is passed to the target function.
  131. // Example:
  132. // In is_once == true case,
  133. // `int&&` -> `int&&`,
  134. // `const int&` -> `int&&`,
  135. // `OwnedWrapper<int>&` -> `int*&&`.
  136. // In is_once == false case,
  137. // `int&&` -> `const int&`,
  138. // `const int&` -> `const int&`,
  139. // `OwnedWrapper<int>&` -> `int* const &`.
  140. template <bool is_once, typename T>
  141. using TransformToUnwrappedType =
  142. typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
  143. // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
  144. // If |is_method| is true, tries to dereference the first argument to support
  145. // smart pointers.
  146. template <bool is_once, bool is_method, typename... Args>
  147. struct MakeUnwrappedTypeListImpl {
  148. using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
  149. };
  150. // Performs special handling for this pointers.
  151. // Example:
  152. // int* -> int*,
  153. // std::unique_ptr<int> -> int*.
  154. template <bool is_once, typename Receiver, typename... Args>
  155. struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
  156. using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
  157. using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
  158. TransformToUnwrappedType<is_once, Args>...>;
  159. };
  160. template <bool is_once, bool is_method, typename... Args>
  161. using MakeUnwrappedTypeList =
  162. typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
  163. // Used below in BindImpl to determine whether to use Invoker::Run or
  164. // Invoker::RunOnce.
  165. // Note: Simply using `kIsOnce ? &Invoker::RunOnce : &Invoker::Run` does not
  166. // work, since the compiler needs to check whether both expressions are
  167. // well-formed. Using `Invoker::Run` with a OnceCallback triggers a
  168. // static_assert, which is why the ternary expression does not compile.
  169. // TODO(crbug.com/752720): Remove this indirection once we have `if constexpr`.
  170. template <typename Invoker>
  171. constexpr auto GetInvokeFunc(std::true_type) {
  172. return Invoker::RunOnce;
  173. }
  174. template <typename Invoker>
  175. constexpr auto GetInvokeFunc(std::false_type) {
  176. return Invoker::Run;
  177. }
  178. template <template <typename> class CallbackT,
  179. typename Functor,
  180. typename... Args>
  181. decltype(auto) BindImpl(Functor&& functor, Args&&... args) {
  182. // This block checks if each |args| matches to the corresponding params of the
  183. // target function. This check does not affect the behavior of Bind, but its
  184. // error message should be more readable.
  185. static constexpr bool kIsOnce = IsOnceCallback<CallbackT<void()>>::value;
  186. using Helper = internal::BindTypeHelper<Functor, Args...>;
  187. using FunctorTraits = typename Helper::FunctorTraits;
  188. using BoundArgsList = typename Helper::BoundArgsList;
  189. using UnwrappedArgsList =
  190. internal::MakeUnwrappedTypeList<kIsOnce, FunctorTraits::is_method,
  191. Args&&...>;
  192. using BoundParamsList = typename Helper::BoundParamsList;
  193. static_assert(internal::AssertBindArgsValidity<
  194. std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
  195. UnwrappedArgsList, BoundParamsList>::ok,
  196. "The bound args need to be convertible to the target params.");
  197. using BindState = internal::MakeBindStateType<Functor, Args...>;
  198. using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
  199. using Invoker = internal::Invoker<BindState, UnboundRunType>;
  200. using CallbackType = CallbackT<UnboundRunType>;
  201. // Store the invoke func into PolymorphicInvoke before casting it to
  202. // InvokeFuncStorage, so that we can ensure its type matches to
  203. // PolymorphicInvoke, to which CallbackType will cast back.
  204. using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
  205. PolymorphicInvoke invoke_func =
  206. GetInvokeFunc<Invoker>(bool_constant<kIsOnce>());
  207. using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
  208. return CallbackType(BindState::Create(
  209. reinterpret_cast<InvokeFuncStorage>(invoke_func),
  210. std::forward<Functor>(functor), std::forward<Args>(args)...));
  211. }
  212. } // namespace internal
  213. // Bind as OnceCallback.
  214. template <typename Functor, typename... Args>
  215. inline OnceCallback<MakeUnboundRunType<Functor, Args...>> BindOnce(
  216. Functor&& functor,
  217. Args&&... args) {
  218. static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
  219. (std::is_rvalue_reference<Functor&&>() &&
  220. !std::is_const<std::remove_reference_t<Functor>>()),
  221. "BindOnce requires non-const rvalue for OnceCallback binding."
  222. " I.e.: base::BindOnce(std::move(callback)).");
  223. return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor),
  224. std::forward<Args>(args)...);
  225. }
  226. // Bind as RepeatingCallback.
  227. template <typename Functor, typename... Args>
  228. inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
  229. BindRepeating(Functor&& functor, Args&&... args) {
  230. static_assert(
  231. !internal::IsOnceCallback<std::decay_t<Functor>>(),
  232. "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
  233. return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor),
  234. std::forward<Args>(args)...);
  235. }
  236. // Unannotated Bind.
  237. // TODO(tzik): Deprecate this and migrate to OnceCallback and
  238. // RepeatingCallback, once they get ready.
  239. template <typename Functor, typename... Args>
  240. inline Callback<MakeUnboundRunType<Functor, Args...>>
  241. Bind(Functor&& functor, Args&&... args) {
  242. return base::BindRepeating(std::forward<Functor>(functor),
  243. std::forward<Args>(args)...);
  244. }
  245. // Special cases for binding to a base::Callback without extra bound arguments.
  246. // We CHECK() the validity of callback to guard against null pointers
  247. // accidentally ending up in posted tasks, causing hard-to-debug crashes.
  248. template <typename Signature>
  249. OnceCallback<Signature> BindOnce(OnceCallback<Signature> callback) {
  250. CHECK(callback);
  251. return callback;
  252. }
  253. template <typename Signature>
  254. OnceCallback<Signature> BindOnce(RepeatingCallback<Signature> callback) {
  255. CHECK(callback);
  256. return callback;
  257. }
  258. template <typename Signature>
  259. RepeatingCallback<Signature> BindRepeating(
  260. RepeatingCallback<Signature> callback) {
  261. CHECK(callback);
  262. return callback;
  263. }
  264. template <typename Signature>
  265. Callback<Signature> Bind(Callback<Signature> callback) {
  266. CHECK(callback);
  267. return callback;
  268. }
  269. // Unretained() allows binding a non-refcounted class, and to disable
  270. // refcounting on arguments that are refcounted objects.
  271. //
  272. // EXAMPLE OF Unretained():
  273. //
  274. // class Foo {
  275. // public:
  276. // void func() { cout << "Foo:f" << endl; }
  277. // };
  278. //
  279. // // In some function somewhere.
  280. // Foo foo;
  281. // OnceClosure foo_callback =
  282. // BindOnce(&Foo::func, Unretained(&foo));
  283. // std::move(foo_callback).Run(); // Prints "Foo:f".
  284. //
  285. // Without the Unretained() wrapper on |&foo|, the above call would fail
  286. // to compile because Foo does not support the AddRef() and Release() methods.
  287. template <typename T>
  288. static inline internal::UnretainedWrapper<T> Unretained(T* o) {
  289. return internal::UnretainedWrapper<T>(o);
  290. }
  291. // RetainedRef() accepts a ref counted object and retains a reference to it.
  292. // When the callback is called, the object is passed as a raw pointer.
  293. //
  294. // EXAMPLE OF RetainedRef():
  295. //
  296. // void foo(RefCountedBytes* bytes) {}
  297. //
  298. // scoped_refptr<RefCountedBytes> bytes = ...;
  299. // OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
  300. // std::move(callback).Run();
  301. //
  302. // Without RetainedRef, the scoped_refptr would try to implicitly convert to
  303. // a raw pointer and fail compilation:
  304. //
  305. // OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
  306. template <typename T>
  307. static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
  308. return internal::RetainedRefWrapper<T>(o);
  309. }
  310. template <typename T>
  311. static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
  312. return internal::RetainedRefWrapper<T>(std::move(o));
  313. }
  314. // Owned() transfers ownership of an object to the callback resulting from
  315. // bind; the object will be deleted when the callback is deleted.
  316. //
  317. // EXAMPLE OF Owned():
  318. //
  319. // void foo(int* arg) { cout << *arg << endl }
  320. //
  321. // int* pn = new int(1);
  322. // RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
  323. //
  324. // foo_callback.Run(); // Prints "1"
  325. // foo_callback.Run(); // Prints "1"
  326. // *pn = 2;
  327. // foo_callback.Run(); // Prints "2"
  328. //
  329. // foo_callback.Reset(); // |pn| is deleted. Also will happen when
  330. // // |foo_callback| goes out of scope.
  331. //
  332. // Without Owned(), someone would have to know to delete |pn| when the last
  333. // reference to the callback is deleted.
  334. template <typename T>
  335. static inline internal::OwnedWrapper<T> Owned(T* o) {
  336. return internal::OwnedWrapper<T>(o);
  337. }
  338. template <typename T, typename Deleter>
  339. static inline internal::OwnedWrapper<T, Deleter> Owned(
  340. std::unique_ptr<T, Deleter>&& ptr) {
  341. return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
  342. }
  343. // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
  344. // through a RepeatingCallback. Logically, this signifies a destructive transfer
  345. // of the state of the argument into the target function. Invoking
  346. // RepeatingCallback::Run() twice on a callback that was created with a Passed()
  347. // argument will CHECK() because the first invocation would have already
  348. // transferred ownership to the target function.
  349. //
  350. // Note that Passed() is not necessary with BindOnce(), as std::move() does the
  351. // same thing. Avoid Passed() in favor of std::move() with BindOnce().
  352. //
  353. // EXAMPLE OF Passed():
  354. //
  355. // void TakesOwnership(std::unique_ptr<Foo> arg) { }
  356. // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
  357. // }
  358. //
  359. // auto f = std::make_unique<Foo>();
  360. //
  361. // // |cb| is given ownership of Foo(). |f| is now NULL.
  362. // // You can use std::move(f) in place of &f, but it's more verbose.
  363. // RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
  364. //
  365. // // Run was never called so |cb| still owns Foo() and deletes
  366. // // it on Reset().
  367. // cb.Reset();
  368. //
  369. // // |cb| is given a new Foo created by CreateFoo().
  370. // cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
  371. //
  372. // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
  373. // // no longer owns Foo() and, if reset, would not delete Foo().
  374. // cb.Run(); // Foo() is now transferred to |arg| and deleted.
  375. // cb.Run(); // This CHECK()s since Foo() already been used once.
  376. //
  377. // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
  378. // best suited for use with the return value of a function or other temporary
  379. // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
  380. // to avoid having to write Passed(std::move(scoper)).
  381. //
  382. // Both versions of Passed() prevent T from being an lvalue reference. The first
  383. // via use of enable_if, and the second takes a T* which will not bind to T&.
  384. template <typename T,
  385. std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
  386. static inline internal::PassedWrapper<T> Passed(T&& scoper) {
  387. return internal::PassedWrapper<T>(std::move(scoper));
  388. }
  389. template <typename T>
  390. static inline internal::PassedWrapper<T> Passed(T* scoper) {
  391. return internal::PassedWrapper<T>(std::move(*scoper));
  392. }
  393. // IgnoreResult() is used to adapt a function or callback with a return type to
  394. // one with a void return. This is most useful if you have a function with,
  395. // say, a pesky ignorable bool return that you want to use with PostTask or
  396. // something else that expect a callback with a void return.
  397. //
  398. // EXAMPLE OF IgnoreResult():
  399. //
  400. // int DoSomething(int arg) { cout << arg << endl; }
  401. //
  402. // // Assign to a callback with a void return type.
  403. // OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
  404. // std::move(cb).Run(1); // Prints "1".
  405. //
  406. // // Prints "2" on |ml|.
  407. // ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
  408. template <typename T>
  409. static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
  410. return internal::IgnoreResultHelper<T>(std::move(data));
  411. }
  412. #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
  413. // RetainBlock() is used to adapt an Objective-C block when Automated Reference
  414. // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
  415. // BindOnce and BindRepeating already support blocks then.
  416. //
  417. // EXAMPLE OF RetainBlock():
  418. //
  419. // // Wrap the block and bind it to a callback.
  420. // OnceCallback<void(int)> cb =
  421. // BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); }));
  422. // std::move(cb).Run(1); // Logs "1".
  423. template <typename R, typename... Args>
  424. base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
  425. return base::mac::ScopedBlock<R (^)(Args...)>(block,
  426. base::scoped_policy::RETAIN);
  427. }
  428. #endif // defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
  429. } // namespace base
  430. #endif // BASE_BIND_H_