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