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