ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 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_ |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 7 | |
Jeremy Roman | 84956fa | 2017-08-16 15:55:20 | [diff] [blame] | 8 | #include <utility> |
| 9 | |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 10 | #include "base/bind_internal.h" |
Sylvain Defresne | ec3270c | 2018-05-31 17:19:15 | [diff] [blame] | 11 | #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 |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 17 | |
brettw@chromium.org | 2429264 | 2012-07-12 20:06:40 | [diff] [blame] | 18 | // ----------------------------------------------------------------------------- |
| 19 | // Usage documentation |
| 20 | // ----------------------------------------------------------------------------- |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 21 | // |
Daniel Cheng | b9d99f5 | 2018-02-19 22:21:51 | [diff] [blame] | 22 | // Overview: |
| 23 | // base::BindOnce() and base::BindRepeating() are helpers for creating |
| 24 | // base::OnceCallback and base::RepeatingCallback objects respectively. |
brettw@chromium.org | 2429264 | 2012-07-12 20:06:40 | [diff] [blame] | 25 | // |
Daniel Cheng | b9d99f5 | 2018-02-19 22:21:51 | [diff] [blame] | 26 | // 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. |
brettw@chromium.org | 2429264 | 2012-07-12 20:06:40 | [diff] [blame] | 48 | // |
| 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. |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 56 | |
| 57 | namespace base { |
| 58 | |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 59 | namespace internal { |
| 60 | |
| 61 | // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback. |
| 62 | template <typename T> |
| 63 | struct IsOnceCallback : std::false_type {}; |
| 64 | |
| 65 | template <typename Signature> |
| 66 | struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {}; |
| 67 | |
Daniel Cheng | a09cb60 | 2017-08-30 13:46:19 | [diff] [blame] | 68 | // 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|. |
| 71 | template <size_t i, |
| 72 | typename Arg, |
| 73 | typename Storage, |
| 74 | typename Unwrapped, |
| 75 | typename Param> |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 76 | struct AssertConstructible { |
Daniel Cheng | a09cb60 | 2017-08-30 13:46:19 | [diff] [blame] | 77 | 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|."); |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 103 | }; |
| 104 | |
| 105 | // Takes three same-length TypeLists, and applies AssertConstructible for each |
| 106 | // triples. |
| 107 | template <typename Index, |
Daniel Cheng | a09cb60 | 2017-08-30 13:46:19 | [diff] [blame] | 108 | typename Args, |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 109 | typename UnwrappedTypeList, |
| 110 | typename ParamsList> |
| 111 | struct AssertBindArgsValidity; |
| 112 | |
| 113 | template <size_t... Ns, |
| 114 | typename... Args, |
| 115 | typename... Unwrapped, |
| 116 | typename... Params> |
Jeremy Roman | 84956fa | 2017-08-16 15:55:20 | [diff] [blame] | 117 | struct AssertBindArgsValidity<std::index_sequence<Ns...>, |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 118 | TypeList<Args...>, |
| 119 | TypeList<Unwrapped...>, |
| 120 | TypeList<Params...>> |
Daniel Cheng | a09cb60 | 2017-08-30 13:46:19 | [diff] [blame] | 121 | : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... { |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 122 | static constexpr bool ok = true; |
| 123 | }; |
| 124 | |
| 125 | // The implementation of TransformToUnwrappedType below. |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 126 | template <bool is_once, typename T> |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 127 | struct TransformToUnwrappedTypeImpl; |
| 128 | |
| 129 | template <typename T> |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 130 | struct TransformToUnwrappedTypeImpl<true, T> { |
Jeremy Roman | 35a31743 | 2017-08-16 22:20:53 | [diff] [blame] | 131 | using StoredType = std::decay_t<T>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 132 | using ForwardType = StoredType&&; |
| 133 | using Unwrapped = decltype(Unwrap(std::declval<ForwardType>())); |
| 134 | }; |
| 135 | |
| 136 | template <typename T> |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 137 | struct TransformToUnwrappedTypeImpl<false, T> { |
Jeremy Roman | 35a31743 | 2017-08-16 22:20:53 | [diff] [blame] | 138 | using StoredType = std::decay_t<T>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 139 | 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: |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 145 | // In is_once == true case, |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 146 | // `int&&` -> `int&&`, |
| 147 | // `const int&` -> `int&&`, |
| 148 | // `OwnedWrapper<int>&` -> `int*&&`. |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 149 | // In is_once == false case, |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 150 | // `int&&` -> `const int&`, |
| 151 | // `const int&` -> `const int&`, |
| 152 | // `OwnedWrapper<int>&` -> `int* const &`. |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 153 | template <bool is_once, typename T> |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 154 | using TransformToUnwrappedType = |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 155 | typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 156 | |
| 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. |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 160 | template <bool is_once, bool is_method, typename... Args> |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 161 | struct MakeUnwrappedTypeListImpl { |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 162 | using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 163 | }; |
| 164 | |
| 165 | // Performs special handling for this pointers. |
| 166 | // Example: |
| 167 | // int* -> int*, |
| 168 | // std::unique_ptr<int> -> int*. |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 169 | template <bool is_once, typename Receiver, typename... Args> |
| 170 | struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> { |
| 171 | using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 172 | using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()), |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 173 | TransformToUnwrappedType<is_once, Args>...>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 174 | }; |
| 175 | |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 176 | template <bool is_once, bool is_method, typename... Args> |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 177 | using MakeUnwrappedTypeList = |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 178 | typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 179 | |
| 180 | } // namespace internal |
| 181 | |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 182 | // Bind as OnceCallback. |
tzik | 401dd367 | 2014-11-26 07:54:58 | [diff] [blame] | 183 | template <typename Functor, typename... Args> |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 184 | inline OnceCallback<MakeUnboundRunType<Functor, Args...>> |
| 185 | BindOnce(Functor&& functor, Args&&... args) { |
Jeremy Roman | 35a31743 | 2017-08-16 22:20:53 | [diff] [blame] | 186 | 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))."); |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 191 | |
| 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 = |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 199 | internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method, |
| 200 | Args&&...>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 201 | using BoundParamsList = typename Helper::BoundParamsList; |
Jeremy Roman | 84956fa | 2017-08-16 15:55:20 | [diff] [blame] | 202 | 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."); |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 206 | |
tzik | 99de02b | 2016-07-01 05:54:12 | [diff] [blame] | 207 | using BindState = internal::MakeBindStateType<Functor, Args...>; |
tzik | caf1d84b | 2016-06-28 12:22:21 | [diff] [blame] | 208 | using UnboundRunType = MakeUnboundRunType<Functor, Args...>; |
tzik | caf1d84b | 2016-06-28 12:22:21 | [diff] [blame] | 209 | using Invoker = internal::Invoker<BindState, UnboundRunType>; |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 210 | 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; |
tzik | efea4f5 | 2018-08-02 15:20:46 | [diff] [blame] | 219 | return CallbackType(BindState::Create( |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 220 | reinterpret_cast<InvokeFuncStorage>(invoke_func), |
tzik | efea4f5 | 2018-08-02 15:20:46 | [diff] [blame] | 221 | std::forward<Functor>(functor), std::forward<Args>(args)...)); |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | // Bind as RepeatingCallback. |
| 225 | template <typename Functor, typename... Args> |
| 226 | inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>> |
| 227 | BindRepeating(Functor&& functor, Args&&... args) { |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 228 | static_assert( |
Jeremy Roman | 35a31743 | 2017-08-16 22:20:53 | [diff] [blame] | 229 | !internal::IsOnceCallback<std::decay_t<Functor>>(), |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 230 | "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move()."); |
| 231 | |
| 232 | // This block checks if each |args| matches to the corresponding params of the |
| 233 | // target function. This check does not affect the behavior of Bind, but its |
| 234 | // error message should be more readable. |
| 235 | using Helper = internal::BindTypeHelper<Functor, Args...>; |
| 236 | using FunctorTraits = typename Helper::FunctorTraits; |
| 237 | using BoundArgsList = typename Helper::BoundArgsList; |
| 238 | using UnwrappedArgsList = |
tzik | d4bb5b7 | 2017-08-28 19:08:52 | [diff] [blame] | 239 | internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method, |
| 240 | Args&&...>; |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 241 | using BoundParamsList = typename Helper::BoundParamsList; |
Jeremy Roman | 84956fa | 2017-08-16 15:55:20 | [diff] [blame] | 242 | static_assert(internal::AssertBindArgsValidity< |
| 243 | std::make_index_sequence<Helper::num_bounds>, BoundArgsList, |
| 244 | UnwrappedArgsList, BoundParamsList>::ok, |
| 245 | "The bound args need to be convertible to the target params."); |
tzik | ae4202e | 2017-07-31 10:41:54 | [diff] [blame] | 246 | |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 247 | using BindState = internal::MakeBindStateType<Functor, Args...>; |
| 248 | using UnboundRunType = MakeUnboundRunType<Functor, Args...>; |
| 249 | using Invoker = internal::Invoker<BindState, UnboundRunType>; |
| 250 | using CallbackType = RepeatingCallback<UnboundRunType>; |
tzik | 1886c27 | 2016-09-08 05:45:38 | [diff] [blame] | 251 | |
| 252 | // Store the invoke func into PolymorphicInvoke before casting it to |
| 253 | // InvokeFuncStorage, so that we can ensure its type matches to |
| 254 | // PolymorphicInvoke, to which CallbackType will cast back. |
| 255 | using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke; |
| 256 | PolymorphicInvoke invoke_func = &Invoker::Run; |
| 257 | |
| 258 | using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage; |
tzik | efea4f5 | 2018-08-02 15:20:46 | [diff] [blame] | 259 | return CallbackType(BindState::Create( |
tzik | 1886c27 | 2016-09-08 05:45:38 | [diff] [blame] | 260 | reinterpret_cast<InvokeFuncStorage>(invoke_func), |
tzik | efea4f5 | 2018-08-02 15:20:46 | [diff] [blame] | 261 | std::forward<Functor>(functor), std::forward<Args>(args)...)); |
ajwong@chromium.org | fccef155 | 2011-11-28 22:13:54 | [diff] [blame] | 262 | } |
| 263 | |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 264 | // Unannotated Bind. |
| 265 | // TODO(tzik): Deprecate this and migrate to OnceCallback and |
| 266 | // RepeatingCallback, once they get ready. |
| 267 | template <typename Functor, typename... Args> |
| 268 | inline Callback<MakeUnboundRunType<Functor, Args...>> |
| 269 | Bind(Functor&& functor, Args&&... args) { |
Yuta Kitamura | d6c13d8e | 2017-12-01 06:09:41 | [diff] [blame] | 270 | return base::BindRepeating(std::forward<Functor>(functor), |
| 271 | std::forward<Args>(args)...); |
tzik | 27d1e31 | 2016-09-13 05:28:59 | [diff] [blame] | 272 | } |
| 273 | |
tzik | c20ed0b | 2017-08-18 22:59:55 | [diff] [blame] | 274 | // Special cases for binding to a base::Callback without extra bound arguments. |
| 275 | template <typename Signature> |
| 276 | OnceCallback<Signature> BindOnce(OnceCallback<Signature> closure) { |
| 277 | return closure; |
| 278 | } |
| 279 | |
| 280 | template <typename Signature> |
| 281 | RepeatingCallback<Signature> BindRepeating( |
| 282 | RepeatingCallback<Signature> closure) { |
| 283 | return closure; |
| 284 | } |
| 285 | |
| 286 | template <typename Signature> |
| 287 | Callback<Signature> Bind(Callback<Signature> closure) { |
| 288 | return closure; |
| 289 | } |
| 290 | |
Peter Kasting | a85265e3 | 2018-02-15 08:30:23 | [diff] [blame] | 291 | // Unretained() allows Bind() to bind a non-refcounted class, and to disable |
| 292 | // refcounting on arguments that are refcounted objects. |
| 293 | // |
| 294 | // EXAMPLE OF Unretained(): |
| 295 | // |
| 296 | // class Foo { |
| 297 | // public: |
| 298 | // void func() { cout << "Foo:f" << endl; } |
| 299 | // }; |
| 300 | // |
| 301 | // // In some function somewhere. |
| 302 | // Foo foo; |
| 303 | // Closure foo_callback = |
| 304 | // Bind(&Foo::func, Unretained(&foo)); |
| 305 | // foo_callback.Run(); // Prints "Foo:f". |
| 306 | // |
| 307 | // Without the Unretained() wrapper on |&foo|, the above call would fail |
| 308 | // to compile because Foo does not support the AddRef() and Release() methods. |
| 309 | template <typename T> |
| 310 | static inline internal::UnretainedWrapper<T> Unretained(T* o) { |
| 311 | return internal::UnretainedWrapper<T>(o); |
| 312 | } |
| 313 | |
| 314 | // RetainedRef() accepts a ref counted object and retains a reference to it. |
| 315 | // When the callback is called, the object is passed as a raw pointer. |
| 316 | // |
| 317 | // EXAMPLE OF RetainedRef(): |
| 318 | // |
| 319 | // void foo(RefCountedBytes* bytes) {} |
| 320 | // |
| 321 | // scoped_refptr<RefCountedBytes> bytes = ...; |
| 322 | // Closure callback = Bind(&foo, base::RetainedRef(bytes)); |
| 323 | // callback.Run(); |
| 324 | // |
| 325 | // Without RetainedRef, the scoped_refptr would try to implicitly convert to |
| 326 | // a raw pointer and fail compilation: |
| 327 | // |
| 328 | // Closure callback = Bind(&foo, bytes); // ERROR! |
| 329 | template <typename T> |
| 330 | static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) { |
| 331 | return internal::RetainedRefWrapper<T>(o); |
| 332 | } |
| 333 | template <typename T> |
| 334 | static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) { |
| 335 | return internal::RetainedRefWrapper<T>(std::move(o)); |
| 336 | } |
| 337 | |
| 338 | // ConstRef() allows binding a constant reference to an argument rather |
| 339 | // than a copy. |
| 340 | // |
| 341 | // EXAMPLE OF ConstRef(): |
| 342 | // |
| 343 | // void foo(int arg) { cout << arg << endl } |
| 344 | // |
| 345 | // int n = 1; |
| 346 | // Closure no_ref = Bind(&foo, n); |
| 347 | // Closure has_ref = Bind(&foo, ConstRef(n)); |
| 348 | // |
| 349 | // no_ref.Run(); // Prints "1" |
| 350 | // has_ref.Run(); // Prints "1" |
| 351 | // |
| 352 | // n = 2; |
| 353 | // no_ref.Run(); // Prints "1" |
| 354 | // has_ref.Run(); // Prints "2" |
| 355 | // |
| 356 | // Note that because ConstRef() takes a reference on |n|, |n| must outlive all |
| 357 | // its bound callbacks. |
| 358 | template <typename T> |
| 359 | static inline internal::ConstRefWrapper<T> ConstRef(const T& o) { |
| 360 | return internal::ConstRefWrapper<T>(o); |
| 361 | } |
| 362 | |
| 363 | // Owned() transfers ownership of an object to the Callback resulting from |
| 364 | // bind; the object will be deleted when the Callback is deleted. |
| 365 | // |
| 366 | // EXAMPLE OF Owned(): |
| 367 | // |
| 368 | // void foo(int* arg) { cout << *arg << endl } |
| 369 | // |
| 370 | // int* pn = new int(1); |
| 371 | // Closure foo_callback = Bind(&foo, Owned(pn)); |
| 372 | // |
| 373 | // foo_callback.Run(); // Prints "1" |
| 374 | // foo_callback.Run(); // Prints "1" |
| 375 | // *n = 2; |
| 376 | // foo_callback.Run(); // Prints "2" |
| 377 | // |
| 378 | // foo_callback.Reset(); // |pn| is deleted. Also will happen when |
| 379 | // // |foo_callback| goes out of scope. |
| 380 | // |
| 381 | // Without Owned(), someone would have to know to delete |pn| when the last |
| 382 | // reference to the Callback is deleted. |
| 383 | template <typename T> |
| 384 | static inline internal::OwnedWrapper<T> Owned(T* o) { |
| 385 | return internal::OwnedWrapper<T>(o); |
| 386 | } |
| 387 | |
| 388 | // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr) |
| 389 | // through a Callback. Logically, this signifies a destructive transfer of |
| 390 | // the state of the argument into the target function. Invoking |
| 391 | // Callback::Run() twice on a Callback that was created with a Passed() |
| 392 | // argument will CHECK() because the first invocation would have already |
| 393 | // transferred ownership to the target function. |
| 394 | // |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 395 | // Note that Passed() is not necessary with BindOnce(), as std::move() does the |
| 396 | // same thing. Avoid Passed() in favor of std::move() with BindOnce(). |
| 397 | // |
Peter Kasting | a85265e3 | 2018-02-15 08:30:23 | [diff] [blame] | 398 | // EXAMPLE OF Passed(): |
| 399 | // |
| 400 | // void TakesOwnership(std::unique_ptr<Foo> arg) { } |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 401 | // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>(); |
Peter Kasting | a85265e3 | 2018-02-15 08:30:23 | [diff] [blame] | 402 | // } |
| 403 | // |
Max Morin | b51cf51 | 2018-02-19 12:49:49 | [diff] [blame] | 404 | // auto f = std::make_unique<Foo>(); |
Peter Kasting | a85265e3 | 2018-02-15 08:30:23 | [diff] [blame] | 405 | // |
| 406 | // // |cb| is given ownership of Foo(). |f| is now NULL. |
| 407 | // // You can use std::move(f) in place of &f, but it's more verbose. |
| 408 | // Closure cb = Bind(&TakesOwnership, Passed(&f)); |
| 409 | // |
| 410 | // // Run was never called so |cb| still owns Foo() and deletes |
| 411 | // // it on Reset(). |
| 412 | // cb.Reset(); |
| 413 | // |
| 414 | // // |cb| is given a new Foo created by CreateFoo(). |
| 415 | // cb = Bind(&TakesOwnership, Passed(CreateFoo())); |
| 416 | // |
| 417 | // // |arg| in TakesOwnership() is given ownership of Foo(). |cb| |
| 418 | // // no longer owns Foo() and, if reset, would not delete Foo(). |
| 419 | // cb.Run(); // Foo() is now transferred to |arg| and deleted. |
| 420 | // cb.Run(); // This CHECK()s since Foo() already been used once. |
| 421 | // |
Peter Kasting | a85265e3 | 2018-02-15 08:30:23 | [diff] [blame] | 422 | // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and |
| 423 | // is best suited for use with the return value of a function or other temporary |
| 424 | // rvalues. The second takes a pointer to the scoper and is just syntactic sugar |
| 425 | // to avoid having to write Passed(std::move(scoper)). |
| 426 | // |
| 427 | // Both versions of Passed() prevent T from being an lvalue reference. The first |
| 428 | // via use of enable_if, and the second takes a T* which will not bind to T&. |
| 429 | template <typename T, |
| 430 | std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr> |
| 431 | static inline internal::PassedWrapper<T> Passed(T&& scoper) { |
| 432 | return internal::PassedWrapper<T>(std::move(scoper)); |
| 433 | } |
| 434 | template <typename T> |
| 435 | static inline internal::PassedWrapper<T> Passed(T* scoper) { |
| 436 | return internal::PassedWrapper<T>(std::move(*scoper)); |
| 437 | } |
| 438 | |
| 439 | // IgnoreResult() is used to adapt a function or Callback with a return type to |
| 440 | // one with a void return. This is most useful if you have a function with, |
| 441 | // say, a pesky ignorable bool return that you want to use with PostTask or |
| 442 | // something else that expect a Callback with a void return. |
| 443 | // |
| 444 | // EXAMPLE OF IgnoreResult(): |
| 445 | // |
| 446 | // int DoSomething(int arg) { cout << arg << endl; } |
| 447 | // |
| 448 | // // Assign to a Callback with a void return type. |
| 449 | // Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething)); |
| 450 | // cb->Run(1); // Prints "1". |
| 451 | // |
| 452 | // // Prints "1" on |ml|. |
| 453 | // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1); |
| 454 | template <typename T> |
| 455 | static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) { |
| 456 | return internal::IgnoreResultHelper<T>(std::move(data)); |
| 457 | } |
| 458 | |
Sylvain Defresne | ec3270c | 2018-05-31 17:19:15 | [diff] [blame] | 459 | #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc) |
| 460 | |
| 461 | // RetainBlock() is used to adapt an Objective-C block when Automated Reference |
| 462 | // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the |
| 463 | // BindOnce and BindRepeating already support blocks then. |
| 464 | // |
| 465 | // EXAMPLE OF RetainBlock(): |
| 466 | // |
| 467 | // // Wrap the block and bind it to a callback. |
| 468 | // Callback<void(int)> cb = Bind(RetainBlock(^(int n) { NSLog(@"%d", n); })); |
| 469 | // cb.Run(1); // Logs "1". |
| 470 | template <typename R, typename... Args> |
| 471 | base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) { |
| 472 | return base::mac::ScopedBlock<R (^)(Args...)>(block, |
| 473 | base::scoped_policy::RETAIN); |
| 474 | } |
| 475 | |
| 476 | #endif // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc) |
| 477 | |
ajwong@chromium.org | b38d357 | 2011-02-15 01:27:38 | [diff] [blame] | 478 | } // namespace base |
| 479 | |
| 480 | #endif // BASE_BIND_H_ |