bind_helpers.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. // This defines a set of argument wrappers and related factory methods that
  5. // can be used specify the refcounting and reference semantics of arguments
  6. // that are bound by the Bind() function in butil/bind.h.
  7. //
  8. // It also defines a set of simple functions and utilities that people want
  9. // when using Callback<> and Bind().
  10. //
  11. //
  12. // ARGUMENT BINDING WRAPPERS
  13. //
  14. // The wrapper functions are butil::Unretained(), butil::Owned(), butil::Passed(),
  15. // butil::ConstRef(), and butil::IgnoreResult().
  16. //
  17. // Unretained() allows Bind() to bind a non-refcounted class, and to disable
  18. // refcounting on arguments that are refcounted objects.
  19. //
  20. // Owned() transfers ownership of an object to the Callback resulting from
  21. // bind; the object will be deleted when the Callback is deleted.
  22. //
  23. // Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr)
  24. // through a Callback. Logically, this signifies a destructive transfer of
  25. // the state of the argument into the target function. Invoking
  26. // Callback::Run() twice on a Callback that was created with a Passed()
  27. // argument will CHECK() because the first invocation would have already
  28. // transferred ownership to the target function.
  29. //
  30. // ConstRef() allows binding a constant reference to an argument rather
  31. // than a copy.
  32. //
  33. // IgnoreResult() is used to adapt a function or Callback with a return type to
  34. // one with a void return. This is most useful if you have a function with,
  35. // say, a pesky ignorable bool return that you want to use with PostTask or
  36. // something else that expect a Callback with a void return.
  37. //
  38. // EXAMPLE OF Unretained():
  39. //
  40. // class Foo {
  41. // public:
  42. // void func() { cout << "Foo:f" << endl; }
  43. // };
  44. //
  45. // // In some function somewhere.
  46. // Foo foo;
  47. // Closure foo_callback =
  48. // Bind(&Foo::func, Unretained(&foo));
  49. // foo_callback.Run(); // Prints "Foo:f".
  50. //
  51. // Without the Unretained() wrapper on |&foo|, the above call would fail
  52. // to compile because Foo does not support the AddRef() and Release() methods.
  53. //
  54. //
  55. // EXAMPLE OF Owned():
  56. //
  57. // void foo(int* arg) { cout << *arg << endl }
  58. //
  59. // int* pn = new int(1);
  60. // Closure foo_callback = Bind(&foo, Owned(pn));
  61. //
  62. // foo_callback.Run(); // Prints "1"
  63. // foo_callback.Run(); // Prints "1"
  64. // *n = 2;
  65. // foo_callback.Run(); // Prints "2"
  66. //
  67. // foo_callback.Reset(); // |pn| is deleted. Also will happen when
  68. // // |foo_callback| goes out of scope.
  69. //
  70. // Without Owned(), someone would have to know to delete |pn| when the last
  71. // reference to the Callback is deleted.
  72. //
  73. //
  74. // EXAMPLE OF ConstRef():
  75. //
  76. // void foo(int arg) { cout << arg << endl }
  77. //
  78. // int n = 1;
  79. // Closure no_ref = Bind(&foo, n);
  80. // Closure has_ref = Bind(&foo, ConstRef(n));
  81. //
  82. // no_ref.Run(); // Prints "1"
  83. // has_ref.Run(); // Prints "1"
  84. //
  85. // n = 2;
  86. // no_ref.Run(); // Prints "1"
  87. // has_ref.Run(); // Prints "2"
  88. //
  89. // Note that because ConstRef() takes a reference on |n|, |n| must outlive all
  90. // its bound callbacks.
  91. //
  92. //
  93. // EXAMPLE OF IgnoreResult():
  94. //
  95. // int DoSomething(int arg) { cout << arg << endl; }
  96. //
  97. // // Assign to a Callback with a void return type.
  98. // Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
  99. // cb->Run(1); // Prints "1".
  100. //
  101. // // Prints "1" on |ml|.
  102. // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
  103. //
  104. //
  105. // EXAMPLE OF Passed():
  106. //
  107. // void TakesOwnership(scoped_ptr<Foo> arg) { }
  108. // scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); }
  109. //
  110. // scoped_ptr<Foo> f(new Foo());
  111. //
  112. // // |cb| is given ownership of Foo(). |f| is now NULL.
  113. // // You can use f.Pass() in place of &f, but it's more verbose.
  114. // Closure cb = Bind(&TakesOwnership, Passed(&f));
  115. //
  116. // // Run was never called so |cb| still owns Foo() and deletes
  117. // // it on Reset().
  118. // cb.Reset();
  119. //
  120. // // |cb| is given a new Foo created by CreateFoo().
  121. // cb = Bind(&TakesOwnership, Passed(CreateFoo()));
  122. //
  123. // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
  124. // // no longer owns Foo() and, if reset, would not delete Foo().
  125. // cb.Run(); // Foo() is now transferred to |arg| and deleted.
  126. // cb.Run(); // This CHECK()s since Foo() already been used once.
  127. //
  128. // Passed() is particularly useful with PostTask() when you are transferring
  129. // ownership of an argument into a task, but don't necessarily know if the
  130. // task will always be executed. This can happen if the task is cancellable
  131. // or if it is posted to a MessageLoopProxy.
  132. //
  133. //
  134. // SIMPLE FUNCTIONS AND UTILITIES.
  135. //
  136. // DoNothing() - Useful for creating a Closure that does nothing when called.
  137. // DeletePointer<T>() - Useful for creating a Closure that will delete a
  138. // pointer when invoked. Only use this when necessary.
  139. // In most cases MessageLoop::DeleteSoon() is a better
  140. // fit.
  141. #ifndef BASE_BIND_HELPERS_H_
  142. #define BASE_BIND_HELPERS_H_
  143. #include "butil/basictypes.h"
  144. #include "butil/callback.h"
  145. #include "butil/memory/weak_ptr.h"
  146. #include "butil/type_traits.h"
  147. namespace butil {
  148. namespace internal {
  149. // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
  150. // for the existence of AddRef() and Release() functions of the correct
  151. // signature.
  152. //
  153. // http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
  154. // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
  155. // http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
  156. // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
  157. //
  158. // The last link in particular show the method used below.
  159. //
  160. // For SFINAE to work with inherited methods, we need to pull some extra tricks
  161. // with multiple inheritance. In the more standard formulation, the overloads
  162. // of Check would be:
  163. //
  164. // template <typename C>
  165. // Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
  166. //
  167. // template <typename C>
  168. // No NotTheCheckWeWant(...);
  169. //
  170. // static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
  171. //
  172. // The problem here is that template resolution will not match
  173. // C::TargetFunc if TargetFunc does not exist directly in C. That is, if
  174. // TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
  175. // |value| will be false. This formulation only checks for whether or
  176. // not TargetFunc exist directly in the class being introspected.
  177. //
  178. // To get around this, we play a dirty trick with multiple inheritance.
  179. // First, We create a class BaseMixin that declares each function that we
  180. // want to probe for. Then we create a class Base that inherits from both T
  181. // (the class we wish to probe) and BaseMixin. Note that the function
  182. // signature in BaseMixin does not need to match the signature of the function
  183. // we are probing for; thus it's easiest to just use void(void).
  184. //
  185. // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
  186. // ambiguous resolution between BaseMixin and T. This lets us write the
  187. // following:
  188. //
  189. // template <typename C>
  190. // No GoodCheck(Helper<&C::TargetFunc>*);
  191. //
  192. // template <typename C>
  193. // Yes GoodCheck(...);
  194. //
  195. // static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
  196. //
  197. // Notice here that the variadic version of GoodCheck() returns Yes here
  198. // instead of No like the previous one. Also notice that we calculate |value|
  199. // by specializing GoodCheck() on Base instead of T.
  200. //
  201. // We've reversed the roles of the variadic, and Helper overloads.
  202. // GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
  203. // substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
  204. // to the variadic version if T has TargetFunc. If T::TargetFunc does not
  205. // exist, then &C::TargetFunc is not ambiguous, and the overload resolution
  206. // will prefer GoodCheck(Helper<&C::TargetFunc>*).
  207. //
  208. // This method of SFINAE will correctly probe for inherited names, but it cannot
  209. // typecheck those names. It's still a good enough sanity check though.
  210. //
  211. // Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
  212. //
  213. // TODO(ajwong): Move to ref_counted.h or type_traits.h when we've vetted
  214. // this works well.
  215. //
  216. // TODO(ajwong): Make this check for Release() as well.
  217. // See http://crbug.com/82038.
  218. template <typename T>
  219. class SupportsAddRefAndRelease {
  220. typedef char Yes[1];
  221. typedef char No[2];
  222. struct BaseMixin {
  223. void AddRef();
  224. };
  225. // MSVC warns when you try to use Base if T has a private destructor, the
  226. // common pattern for refcounted types. It does this even though no attempt to
  227. // instantiate Base is made. We disable the warning for this definition.
  228. #if defined(OS_WIN)
  229. #pragma warning(push)
  230. #pragma warning(disable:4624)
  231. #endif
  232. struct Base : public T, public BaseMixin {
  233. };
  234. #if defined(OS_WIN)
  235. #pragma warning(pop)
  236. #endif
  237. template <void(BaseMixin::*)(void)> struct Helper {};
  238. template <typename C>
  239. static No& Check(Helper<&C::AddRef>*);
  240. template <typename >
  241. static Yes& Check(...);
  242. public:
  243. static const bool value = sizeof(Check<Base>(0)) == sizeof(Yes);
  244. };
  245. // Helpers to assert that arguments of a recounted type are bound with a
  246. // scoped_refptr.
  247. template <bool IsClasstype, typename T>
  248. struct UnsafeBindtoRefCountedArgHelper : false_type {
  249. };
  250. template <typename T>
  251. struct UnsafeBindtoRefCountedArgHelper<true, T>
  252. : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
  253. };
  254. template <typename T>
  255. struct UnsafeBindtoRefCountedArg : false_type {
  256. };
  257. template <typename T>
  258. struct UnsafeBindtoRefCountedArg<T*>
  259. : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
  260. };
  261. template <typename T>
  262. class HasIsMethodTag {
  263. typedef char Yes[1];
  264. typedef char No[2];
  265. template <typename U>
  266. static Yes& Check(typename U::IsMethod*);
  267. template <typename U>
  268. static No& Check(...);
  269. public:
  270. static const bool value = sizeof(Check<T>(0)) == sizeof(Yes);
  271. };
  272. template <typename T>
  273. class UnretainedWrapper {
  274. public:
  275. explicit UnretainedWrapper(T* o) : ptr_(o) {}
  276. T* get() const { return ptr_; }
  277. private:
  278. T* ptr_;
  279. };
  280. template <typename T>
  281. class ConstRefWrapper {
  282. public:
  283. explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
  284. const T& get() const { return *ptr_; }
  285. private:
  286. const T* ptr_;
  287. };
  288. template <typename T>
  289. struct IgnoreResultHelper {
  290. explicit IgnoreResultHelper(T functor) : functor_(functor) {}
  291. T functor_;
  292. };
  293. template <typename T>
  294. struct IgnoreResultHelper<Callback<T> > {
  295. explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {}
  296. const Callback<T>& functor_;
  297. };
  298. // An alternate implementation is to avoid the destructive copy, and instead
  299. // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
  300. // a class that is essentially a scoped_ptr<>.
  301. //
  302. // The current implementation has the benefit though of leaving ParamTraits<>
  303. // fully in callback_internal.h as well as avoiding type conversions during
  304. // storage.
  305. template <typename T>
  306. class OwnedWrapper {
  307. public:
  308. explicit OwnedWrapper(T* o) : ptr_(o) {}
  309. ~OwnedWrapper() { delete ptr_; }
  310. T* get() const { return ptr_; }
  311. OwnedWrapper(const OwnedWrapper& other) {
  312. ptr_ = other.ptr_;
  313. other.ptr_ = NULL;
  314. }
  315. private:
  316. mutable T* ptr_;
  317. };
  318. // PassedWrapper is a copyable adapter for a scoper that ignores const.
  319. //
  320. // It is needed to get around the fact that Bind() takes a const reference to
  321. // all its arguments. Because Bind() takes a const reference to avoid
  322. // unnecessary copies, it is incompatible with movable-but-not-copyable
  323. // types; doing a destructive "move" of the type into Bind() would violate
  324. // the const correctness.
  325. //
  326. // This conundrum cannot be solved without either C++11 rvalue references or
  327. // a O(2^n) blowup of Bind() templates to handle each combination of regular
  328. // types and movable-but-not-copyable types. Thus we introduce a wrapper type
  329. // that is copyable to transmit the correct type information down into
  330. // BindState<>. Ignoring const in this type makes sense because it is only
  331. // created when we are explicitly trying to do a destructive move.
  332. //
  333. // Two notes:
  334. // 1) PassedWrapper supports any type that has a "Pass()" function.
  335. // This is intentional. The whitelisting of which specific types we
  336. // support is maintained by CallbackParamTraits<>.
  337. // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
  338. // scoper to a Callback and allow the Callback to execute once.
  339. template <typename T>
  340. class PassedWrapper {
  341. public:
  342. explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {}
  343. PassedWrapper(const PassedWrapper& other)
  344. : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) {
  345. }
  346. T Pass() const {
  347. CHECK(is_valid_);
  348. is_valid_ = false;
  349. return scoper_.Pass();
  350. }
  351. private:
  352. mutable bool is_valid_;
  353. mutable T scoper_;
  354. };
  355. // Unwrap the stored parameters for the wrappers above.
  356. template <typename T>
  357. struct UnwrapTraits {
  358. typedef const T& ForwardType;
  359. static ForwardType Unwrap(const T& o) { return o; }
  360. };
  361. template <typename T>
  362. struct UnwrapTraits<UnretainedWrapper<T> > {
  363. typedef T* ForwardType;
  364. static ForwardType Unwrap(UnretainedWrapper<T> unretained) {
  365. return unretained.get();
  366. }
  367. };
  368. template <typename T>
  369. struct UnwrapTraits<ConstRefWrapper<T> > {
  370. typedef const T& ForwardType;
  371. static ForwardType Unwrap(ConstRefWrapper<T> const_ref) {
  372. return const_ref.get();
  373. }
  374. };
  375. template <typename T>
  376. struct UnwrapTraits<scoped_refptr<T> > {
  377. typedef T* ForwardType;
  378. static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); }
  379. };
  380. template <typename T>
  381. struct UnwrapTraits<WeakPtr<T> > {
  382. typedef const WeakPtr<T>& ForwardType;
  383. static ForwardType Unwrap(const WeakPtr<T>& o) { return o; }
  384. };
  385. template <typename T>
  386. struct UnwrapTraits<OwnedWrapper<T> > {
  387. typedef T* ForwardType;
  388. static ForwardType Unwrap(const OwnedWrapper<T>& o) {
  389. return o.get();
  390. }
  391. };
  392. template <typename T>
  393. struct UnwrapTraits<PassedWrapper<T> > {
  394. typedef T ForwardType;
  395. static T Unwrap(PassedWrapper<T>& o) {
  396. return o.Pass();
  397. }
  398. };
  399. // Utility for handling different refcounting semantics in the Bind()
  400. // function.
  401. template <bool is_method, typename T>
  402. struct MaybeRefcount;
  403. template <typename T>
  404. struct MaybeRefcount<false, T> {
  405. static void AddRef(const T&) {}
  406. static void Release(const T&) {}
  407. };
  408. template <typename T, size_t n>
  409. struct MaybeRefcount<false, T[n]> {
  410. static void AddRef(const T*) {}
  411. static void Release(const T*) {}
  412. };
  413. template <typename T>
  414. struct MaybeRefcount<true, T> {
  415. static void AddRef(const T&) {}
  416. static void Release(const T&) {}
  417. };
  418. template <typename T>
  419. struct MaybeRefcount<true, T*> {
  420. static void AddRef(T* o) { o->AddRef(); }
  421. static void Release(T* o) { o->Release(); }
  422. };
  423. // No need to additionally AddRef() and Release() since we are storing a
  424. // scoped_refptr<> inside the storage object already.
  425. template <typename T>
  426. struct MaybeRefcount<true, scoped_refptr<T> > {
  427. static void AddRef(const scoped_refptr<T>& o) {}
  428. static void Release(const scoped_refptr<T>& o) {}
  429. };
  430. template <typename T>
  431. struct MaybeRefcount<true, const T*> {
  432. static void AddRef(const T* o) { o->AddRef(); }
  433. static void Release(const T* o) { o->Release(); }
  434. };
  435. // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
  436. // method. It is used internally by Bind() to select the correct
  437. // InvokeHelper that will no-op itself in the event the WeakPtr<> for
  438. // the target object is invalidated.
  439. //
  440. // P1 should be the type of the object that will be received of the method.
  441. template <bool IsMethod, typename P1>
  442. struct IsWeakMethod : public false_type {};
  443. template <typename T>
  444. struct IsWeakMethod<true, WeakPtr<T> > : public true_type {};
  445. template <typename T>
  446. struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T> > > : public true_type {};
  447. } // namespace internal
  448. template <typename T>
  449. static inline internal::UnretainedWrapper<T> Unretained(T* o) {
  450. return internal::UnretainedWrapper<T>(o);
  451. }
  452. template <typename T>
  453. static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
  454. return internal::ConstRefWrapper<T>(o);
  455. }
  456. template <typename T>
  457. static inline internal::OwnedWrapper<T> Owned(T* o) {
  458. return internal::OwnedWrapper<T>(o);
  459. }
  460. // We offer 2 syntaxes for calling Passed(). The first takes a temporary and
  461. // is best suited for use with the return value of a function. The second
  462. // takes a pointer to the scoper and is just syntactic sugar to avoid having
  463. // to write Passed(scoper.Pass()).
  464. template <typename T>
  465. static inline internal::PassedWrapper<T> Passed(T scoper) {
  466. return internal::PassedWrapper<T>(scoper.Pass());
  467. }
  468. template <typename T>
  469. static inline internal::PassedWrapper<T> Passed(T* scoper) {
  470. return internal::PassedWrapper<T>(scoper->Pass());
  471. }
  472. template <typename T>
  473. static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
  474. return internal::IgnoreResultHelper<T>(data);
  475. }
  476. template <typename T>
  477. static inline internal::IgnoreResultHelper<Callback<T> >
  478. IgnoreResult(const Callback<T>& data) {
  479. return internal::IgnoreResultHelper<Callback<T> >(data);
  480. }
  481. BASE_EXPORT void DoNothing();
  482. template<typename T>
  483. void DeletePointer(T* obj) {
  484. delete obj;
  485. }
  486. } // namespace butil
  487. #endif // BASE_BIND_HELPERS_H_