Updating trunk VERSION from 935.0 to 936.0
[chromium-blink-merge.git] / base / bind_helpers.h
blobd7ddb2c49bab76629c952d132b30d9b6263b8a4c
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.
5 // This defines a set of argument wrappers and related factory methods that
6 // can be used specify the refcounting and reference semantics of arguments
7 // that are bound by the Bind() function in base/bind.h.
8 //
9 // The public functions are base::Unretained(), base::Owned(),
10 // base::ConstRef(), and base::IgnoreReturn().
12 // Unretained() allows Bind() to bind a non-refcounted class, and to disable
13 // refcounting on arguments that are refcounted objects.
14 // Owned() transfers ownership of an object to the Callback resulting from
15 // bind; the object will be deleted when the Callback is deleted.
16 // ConstRef() allows binding a constant reference to an argument rather
17 // than a copy.
18 // IgnoreReturn() is used to adapt a 0-argument Callback with a return type to
19 // a Closure. This is useful if you need to PostTask with a function that has
20 // a return value that you don't care about.
23 // EXAMPLE OF Unretained():
25 // class Foo {
26 // public:
27 // void func() { cout << "Foo:f" << endl; }
28 // };
30 // // In some function somewhere.
31 // Foo foo;
32 // Closure foo_callback =
33 // Bind(&Foo::func, Unretained(&foo));
34 // foo_callback.Run(); // Prints "Foo:f".
36 // Without the Unretained() wrapper on |&foo|, the above call would fail
37 // to compile because Foo does not support the AddRef() and Release() methods.
40 // EXAMPLE OF Owned():
42 // void foo(int* arg) { cout << *arg << endl }
44 // int* pn = new int(1);
45 // Closure foo_callback = Bind(&foo, Owned(pn));
47 // foo_callback.Run(); // Prints "1"
48 // foo_callback.Run(); // Prints "1"
49 // *n = 2;
50 // foo_callback.Run(); // Prints "2"
52 // foo_callback.Reset(); // |pn| is deleted. Also will happen when
53 // // |foo_callback| goes out of scope.
55 // Without Owned(), someone would have to know to delete |pn| when the last
56 // reference to the Callback is deleted.
59 // EXAMPLE OF ConstRef():
61 // void foo(int arg) { cout << arg << endl }
63 // int n = 1;
64 // Closure no_ref = Bind(&foo, n);
65 // Closure has_ref = Bind(&foo, ConstRef(n));
67 // no_ref.Run(); // Prints "1"
68 // has_ref.Run(); // Prints "1"
70 // n = 2;
71 // no_ref.Run(); // Prints "1"
72 // has_ref.Run(); // Prints "2"
74 // Note that because ConstRef() takes a reference on |n|, |n| must outlive all
75 // its bound callbacks.
78 // EXAMPLE OF IgnoreReturn():
80 // int DoSomething(int arg) { cout << arg << endl; }
81 // Callback<int(void)> cb = Bind(&DoSomething, 1);
82 // Closure c = IgnoreReturn(cb); // Prints "1"
83 // or
84 // ml->PostTask(FROM_HERE, IgnoreReturn(cb)); // Prints "1" on |ml|
86 #ifndef BASE_BIND_HELPERS_H_
87 #define BASE_BIND_HELPERS_H_
88 #pragma once
90 #include "base/basictypes.h"
91 #include "base/bind.h"
92 #include "base/callback.h"
93 #include "base/memory/weak_ptr.h"
94 #include "base/template_util.h"
96 namespace base {
97 namespace internal {
99 // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
100 // for the existence of AddRef() and Release() functions of the correct
101 // signature.
103 // http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
104 // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
105 // http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
106 // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
108 // The last link in particular show the method used below.
110 // For SFINAE to work with inherited methods, we need to pull some extra tricks
111 // with multiple inheritance. In the more standard formulation, the overloads
112 // of Check would be:
114 // template <typename C>
115 // Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
117 // template <typename C>
118 // No NotTheCheckWeWant(...);
120 // static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
122 // The problem here is that template resolution will not match
123 // C::TargetFunc if TargetFunc does not exist directly in C. That is, if
124 // TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
125 // |value| will be false. This formulation only checks for whether or
126 // not TargetFunc exist directly in the class being introspected.
128 // To get around this, we play a dirty trick with multiple inheritance.
129 // First, We create a class BaseMixin that declares each function that we
130 // want to probe for. Then we create a class Base that inherits from both T
131 // (the class we wish to probe) and BaseMixin. Note that the function
132 // signature in BaseMixin does not need to match the signature of the function
133 // we are probing for; thus it's easiest to just use void(void).
135 // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
136 // ambiguous resolution between BaseMixin and T. This lets us write the
137 // following:
139 // template <typename C>
140 // No GoodCheck(Helper<&C::TargetFunc>*);
142 // template <typename C>
143 // Yes GoodCheck(...);
145 // static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
147 // Notice here that the variadic version of GoodCheck() returns Yes here
148 // instead of No like the previous one. Also notice that we calculate |value|
149 // by specializing GoodCheck() on Base instead of T.
151 // We've reversed the roles of the variadic, and Helper overloads.
152 // GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
153 // substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
154 // to the variadic version if T has TargetFunc. If T::TargetFunc does not
155 // exist, then &C::TargetFunc is not ambiguous, and the overload resolution
156 // will prefer GoodCheck(Helper<&C::TargetFunc>*).
158 // This method of SFINAE will correctly probe for inherited names, but it cannot
159 // typecheck those names. It's still a good enough sanity check though.
161 // Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
163 // TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted
164 // this works well.
166 // TODO(ajwong): Make this check for Release() as well.
167 // See http://crbug.com/82038.
168 template <typename T>
169 class SupportsAddRefAndRelease {
170 typedef char Yes[1];
171 typedef char No[2];
173 struct BaseMixin {
174 void AddRef();
177 // MSVC warns when you try to use Base if T has a private destructor, the
178 // common pattern for refcounted types. It does this even though no attempt to
179 // instantiate Base is made. We disable the warning for this definition.
180 #if defined(OS_WIN)
181 #pragma warning(disable:4624)
182 #endif
183 struct Base : public T, public BaseMixin {
185 #if defined(OS_WIN)
186 #pragma warning(default:4624)
187 #endif
189 template <void(BaseMixin::*)(void)> struct Helper {};
191 template <typename C>
192 static No& Check(Helper<&C::AddRef>*);
194 template <typename >
195 static Yes& Check(...);
197 public:
198 static const bool value = sizeof(Check<Base>(0)) == sizeof(Yes);
202 // Helpers to assert that arguments of a recounted type are bound with a
203 // scoped_refptr.
204 template <bool IsClasstype, typename T>
205 struct UnsafeBindtoRefCountedArgHelper : false_type {
208 template <typename T>
209 struct UnsafeBindtoRefCountedArgHelper<true, T>
210 : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
213 template <typename T>
214 struct UnsafeBindtoRefCountedArg : false_type {
217 template <typename T>
218 struct UnsafeBindtoRefCountedArg<T*>
219 : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
223 template <typename T>
224 class UnretainedWrapper {
225 public:
226 explicit UnretainedWrapper(T* o) : ptr_(o) {}
227 T* get() const { return ptr_; }
228 private:
229 T* ptr_;
232 template <typename T>
233 class ConstRefWrapper {
234 public:
235 explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
236 const T& get() const { return *ptr_; }
237 private:
238 const T* ptr_;
241 // An alternate implementation is to avoid the destructive copy, and instead
242 // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
243 // a class that is essentially a scoped_ptr<>.
245 // The current implementation has the benefit though of leaving ParamTraits<>
246 // fully in callback_internal.h as well as avoiding type conversions during
247 // storage.
248 template <typename T>
249 class OwnedWrapper {
250 public:
251 explicit OwnedWrapper(T* o) : ptr_(o) {}
252 ~OwnedWrapper() { delete ptr_; }
253 T* get() const { return ptr_; }
254 OwnedWrapper(const OwnedWrapper& other) {
255 ptr_ = other.ptr_;
256 other.ptr_ = NULL;
259 private:
260 mutable T* ptr_;
264 // Unwrap the stored parameters for the wrappers above.
265 template <typename T>
266 T Unwrap(T o) { return o; }
268 template <typename T>
269 T* Unwrap(UnretainedWrapper<T> unretained) { return unretained.get(); }
271 template <typename T>
272 const T& Unwrap(ConstRefWrapper<T> const_ref) {
273 return const_ref.get();
276 template <typename T>
277 T* Unwrap(const scoped_refptr<T>& o) { return o.get(); }
279 template <typename T>
280 const WeakPtr<T>& Unwrap(const WeakPtr<T>& o) { return o; }
282 template <typename T>
283 T* Unwrap(const OwnedWrapper<T>& o) {
284 return o.get();
287 // Utility for handling different refcounting semantics in the Bind()
288 // function.
289 template <typename IsMethod, typename T>
290 struct MaybeRefcount;
292 template <typename T>
293 struct MaybeRefcount<base::false_type, T> {
294 static void AddRef(const T&) {}
295 static void Release(const T&) {}
298 template <typename T, size_t n>
299 struct MaybeRefcount<base::false_type, T[n]> {
300 static void AddRef(const T*) {}
301 static void Release(const T*) {}
304 template <typename T>
305 struct MaybeRefcount<base::true_type, T*> {
306 static void AddRef(T* o) { o->AddRef(); }
307 static void Release(T* o) { o->Release(); }
310 template <typename T>
311 struct MaybeRefcount<base::true_type, UnretainedWrapper<T> > {
312 static void AddRef(const UnretainedWrapper<T>&) {}
313 static void Release(const UnretainedWrapper<T>&) {}
316 template <typename T>
317 struct MaybeRefcount<base::true_type, OwnedWrapper<T> > {
318 static void AddRef(const OwnedWrapper<T>&) {}
319 static void Release(const OwnedWrapper<T>&) {}
322 // No need to additionally AddRef() and Release() since we are storing a
323 // scoped_refptr<> inside the storage object already.
324 template <typename T>
325 struct MaybeRefcount<base::true_type, scoped_refptr<T> > {
326 static void AddRef(const scoped_refptr<T>& o) {}
327 static void Release(const scoped_refptr<T>& o) {}
330 template <typename T>
331 struct MaybeRefcount<base::true_type, const T*> {
332 static void AddRef(const T* o) { o->AddRef(); }
333 static void Release(const T* o) { o->Release(); }
336 template <typename T>
337 struct MaybeRefcount<base::true_type, WeakPtr<T> > {
338 static void AddRef(const WeakPtr<T>&) {}
339 static void Release(const WeakPtr<T>&) {}
342 template <typename R>
343 void VoidReturnAdapter(Callback<R(void)> callback) {
344 callback.Run();
347 } // namespace internal
349 template <typename T>
350 inline internal::UnretainedWrapper<T> Unretained(T* o) {
351 return internal::UnretainedWrapper<T>(o);
354 template <typename T>
355 inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
356 return internal::ConstRefWrapper<T>(o);
359 template <typename T>
360 inline internal::OwnedWrapper<T> Owned(T* o) {
361 return internal::OwnedWrapper<T>(o);
364 template <typename R>
365 Closure IgnoreReturn(Callback<R(void)> callback) {
366 return Bind(&internal::VoidReturnAdapter<R>, callback);
369 } // namespace base
371 #endif // BASE_BIND_HELPERS_H_