bind_helpers.h revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
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// 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() and base::ConstRef().
10// Unretained() allows Bind() to bind a non-refcounted class.
11// ConstRef() allows binding a constant reference to an argument rather
12// than a copy.
13//
14//
15// EXAMPLE OF Unretained():
16//
17//   class Foo {
18//    public:
19//     void func() { cout << "Foo:f" << endl;
20//   };
21//
22//   // In some function somewhere.
23//   Foo foo;
24//   Callback<void(void)> foo_callback =
25//       Bind(&Foo::func, Unretained(&foo));
26//   foo_callback.Run();  // Prints "Foo:f".
27//
28// Without the Unretained() wrapper on |&foo|, the above call would fail
29// to compile because Foo does not support the AddRef() and Release() methods.
30//
31//
32// EXAMPLE OF ConstRef();
33//   void foo(int arg) { cout << arg << endl }
34//
35//   int n = 1;
36//   Callback<void(void)> no_ref = Bind(&foo, n);
37//   Callback<void(void)> has_ref = Bind(&foo, ConstRef(n));
38//
39//   no_ref.Run();  // Prints "1"
40//   has_ref.Run();  // Prints "1"
41//
42//   n = 2;
43//   no_ref.Run();  // Prints "1"
44//   has_ref.Run();  // Prints "2"
45//
46// Note that because ConstRef() takes a reference on |n|, |n| must outlive all
47// its bound callbacks.
48//
49
50#ifndef BASE_BIND_HELPERS_H_
51#define BASE_BIND_HELPERS_H_
52#pragma once
53
54#include "base/basictypes.h"
55#include "base/template_util.h"
56
57namespace base {
58namespace internal {
59
60// Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
61// for the existence of AddRef() and Release() functions of the correct
62// signature.
63//
64// http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
65// http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
66// http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
67// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
68//
69// The last link in particular show the method used below.
70//
71// For SFINAE to work with inherited methods, we need to pull some extra tricks
72// with multiple inheritance.  In the more standard formulation, the overloads
73// of Check would be:
74//
75//   template <typename C>
76//   Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
77//
78//   template <typename C>
79//   No NotTheCheckWeWant(...);
80//
81//   static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
82//
83// The problem here is that template resolution will not match
84// C::TargetFunc if TargetFunc does not exist directly in C.  That is, if
85// TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
86// |value| will be false.  This formulation only checks for whether or
87// not TargetFunc exist directly in the class being introspected.
88//
89// To get around this, we play a dirty trick with multiple inheritance.
90// First, We create a class BaseMixin that declares each function that we
91// want to probe for.  Then we create a class Base that inherits from both T
92// (the class we wish to probe) and BaseMixin.  Note that the function
93// signature in BaseMixin does not need to match the signature of the function
94// we are probing for; thus it's easiest to just use void(void).
95//
96// Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
97// ambiguous resolution between BaseMixin and T.  This lets us write the
98// following:
99//
100//   template <typename C>
101//   No GoodCheck(Helper<&C::TargetFunc>*);
102//
103//   template <typename C>
104//   Yes GoodCheck(...);
105//
106//   static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
107//
108// Notice here that the variadic version of GoodCheck() returns Yes here
109// instead of No like the previous one. Also notice that we calculate |value|
110// by specializing GoodCheck() on Base instead of T.
111//
112// We've reversed the roles of the variadic, and Helper overloads.
113// GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
114// substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
115// to the variadic version if T has TargetFunc.  If T::TargetFunc does not
116// exist, then &C::TargetFunc is not ambiguous, and the overload resolution
117// will prefer GoodCheck(Helper<&C::TargetFunc>*).
118//
119// This method of SFINAE will correctly probe for inherited names, but it cannot
120// typecheck those names.  It's still a good enough sanity check though.
121//
122// Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
123//
124// TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted
125// this works well.
126template <typename T>
127class SupportsAddRefAndRelease {
128  typedef char Yes[1];
129  typedef char No[2];
130
131  struct BaseMixin {
132    void AddRef();
133    void Release();
134  };
135
136  struct Base : public T, public BaseMixin {
137  };
138
139  template <void(BaseMixin::*)(void)>  struct Helper {};
140
141  template <typename C>
142  static No& Check(Helper<&C::AddRef>*, Helper<&C::Release>*);
143
144  template <typename >
145  static Yes& Check(...);
146
147 public:
148  static const bool value = sizeof(Check<Base>(0,0)) == sizeof(Yes);
149};
150
151
152// Helpers to assert that arguments of a recounted type are bound with a
153// scoped_refptr.
154template <bool IsClasstype, typename T>
155struct UnsafeBindtoRefCountedArgHelper : false_type {
156};
157
158template <typename T>
159struct UnsafeBindtoRefCountedArgHelper<true, T>
160    : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
161};
162
163template <typename T>
164struct UnsafeBindtoRefCountedArg
165    : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
166};
167
168
169template <typename T>
170class UnretainedWrapper {
171 public:
172  explicit UnretainedWrapper(T* o) : obj_(o) {}
173  T* get() { return obj_; }
174 private:
175  T* obj_;
176};
177
178template <typename T>
179class ConstRefWrapper {
180 public:
181  explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
182  const T& get() { return *ptr_; }
183 private:
184  const T* ptr_;
185};
186
187
188// Unwrap the stored parameters for the wrappers above.
189template <typename T>
190T Unwrap(T o) { return o; }
191
192template <typename T>
193T* Unwrap(UnretainedWrapper<T> unretained) { return unretained.get(); }
194
195template <typename T>
196const T& Unwrap(ConstRefWrapper<T> const_ref) {
197  return const_ref.get();
198}
199
200
201// Utility for handling different refcounting semantics in the Bind()
202// function.
203template <typename ref, typename T>
204struct MaybeRefcount;
205
206template <typename T>
207struct MaybeRefcount<base::false_type, T> {
208  static void AddRef(const T&) {}
209  static void Release(const T&) {}
210};
211
212template <typename T, size_t n>
213struct MaybeRefcount<base::false_type, T[n]> {
214  static void AddRef(const T*) {}
215  static void Release(const T*) {}
216};
217
218template <typename T>
219struct MaybeRefcount<base::true_type, UnretainedWrapper<T> > {
220  static void AddRef(const UnretainedWrapper<T>&) {}
221  static void Release(const UnretainedWrapper<T>&) {}
222};
223
224template <typename T>
225struct MaybeRefcount<base::true_type, T*> {
226  static void AddRef(T* o) { o->AddRef(); }
227  static void Release(T* o) { o->Release(); }
228};
229
230template <typename T>
231struct MaybeRefcount<base::true_type, const T*> {
232  static void AddRef(const T* o) { o->AddRef(); }
233  static void Release(const T* o) { o->Release(); }
234};
235
236
237// This is a typetraits object that's used to convert an argument type into a
238// type suitable for storage.  In particular, it strips off references, and
239// converts arrays to pointers.
240//
241// This array type becomes an issue because we are passing bound parameters by
242// const reference. In this case, we end up passing an actual array type in the
243// initializer list which C++ does not allow.  This will break passing of
244// C-string literals.
245template <typename T>
246struct BindType {
247  typedef T StorageType;
248};
249
250// This should almost be impossible to trigger unless someone manually
251// specifies type of the bind parameters.  However, in case they do,
252// this will guard against us accidentally storing a reference parameter.
253template <typename T>
254struct BindType<T&> {
255  typedef T StorageType;
256};
257
258// Note that for array types, we implicitly add a const in the conversion. This
259// means that it is not possible to bind array arguments to functions that take
260// a non-const pointer. Trying to specialize the template based on a "const
261// T[n]" does not seem to match correctly, so we are stuck with this
262// restriction.
263template <typename T, size_t n>
264struct BindType<T[n]> {
265  typedef const T* StorageType;
266};
267
268template <typename T>
269struct BindType<T[]> {
270  typedef const T* StorageType;
271};
272
273}  // namespace internal
274
275template <typename T>
276inline internal::UnretainedWrapper<T> Unretained(T* o) {
277  return internal::UnretainedWrapper<T>(o);
278}
279
280template <typename T>
281inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
282  return internal::ConstRefWrapper<T>(o);
283}
284
285}  // namespace base
286
287#endif  // BASE_BIND_HELPERS_H_
288