• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2012 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 // Bind() is an overloaded function that converts method calls into function
12 // objects (aka functors). The method object is captured as a scoped_refptr<> if
13 // possible, and as a raw pointer otherwise. Any arguments to the method are
14 // captured by value. The return value of Bind is a stateful, nullary function
15 // object. Care should be taken about the lifetime of objects captured by
16 // Bind(); the returned functor knows nothing about the lifetime of a non
17 // ref-counted method object or any arguments passed by pointer, and calling the
18 // functor with a destroyed object will surely do bad things.
19 //
20 // To prevent the method object from being captured as a scoped_refptr<>, you
21 // can use Unretained. But this should only be done when absolutely necessary,
22 // and when the caller knows the extra reference isn't needed.
23 //
24 // Example usage:
25 //   struct Foo {
26 //     int Test1() { return 42; }
27 //     int Test2() const { return 52; }
28 //     int Test3(int x) { return x*x; }
29 //     float Test4(int x, float y) { return x + y; }
30 //   };
31 //
32 //   int main() {
33 //     Foo foo;
34 //     cout << rtc::Bind(&Foo::Test1, &foo)() << endl;
35 //     cout << rtc::Bind(&Foo::Test2, &foo)() << endl;
36 //     cout << rtc::Bind(&Foo::Test3, &foo, 3)() << endl;
37 //     cout << rtc::Bind(&Foo::Test4, &foo, 7, 8.5f)() << endl;
38 //   }
39 //
40 // Example usage of ref counted objects:
41 //   struct Bar {
42 //     int AddRef();
43 //     int Release();
44 //
45 //     void Test() {}
46 //     void BindThis() {
47 //       // The functor passed to AsyncInvoke() will keep this object alive.
48 //       invoker.AsyncInvoke(RTC_FROM_HERE,rtc::Bind(&Bar::Test, this));
49 //     }
50 //   };
51 //
52 //   int main() {
53 //     rtc::scoped_refptr<Bar> bar = new rtc::RefCountedObject<Bar>();
54 //     auto functor = rtc::Bind(&Bar::Test, bar);
55 //     bar = nullptr;
56 //     // The functor stores an internal scoped_refptr<Bar>, so this is safe.
57 //     functor();
58 //   }
59 //
60 
61 #ifndef RTC_BASE_BIND_H_
62 #define RTC_BASE_BIND_H_
63 
64 #include <tuple>
65 #include <type_traits>
66 
67 #include "api/scoped_refptr.h"
68 
69 #define NONAME
70 
71 namespace rtc {
72 namespace detail {
73 // This is needed because the template parameters in Bind can't be resolved
74 // if they're used both as parameters of the function pointer type and as
75 // parameters to Bind itself: the function pointer parameters are exact
76 // matches to the function prototype, but the parameters to bind have
77 // references stripped. This trick allows the compiler to dictate the Bind
78 // parameter types rather than deduce them.
79 template <class T>
80 struct identity {
81   typedef T type;
82 };
83 
84 // IsRefCounted<T>::value will be true for types that can be used in
85 // rtc::scoped_refptr<T>, i.e. types that implements nullary functions AddRef()
86 // and Release(), regardless of their return types. AddRef() and Release() can
87 // be defined in T or any superclass of T.
88 template <typename T>
89 class IsRefCounted {
90   // This is a complex implementation detail done with SFINAE.
91 
92   // Define types such that sizeof(Yes) != sizeof(No).
93   struct Yes {
94     char dummy[1];
95   };
96   struct No {
97     char dummy[2];
98   };
99   // Define two overloaded template functions with return types of different
100   // size. This way, we can use sizeof() on the return type to determine which
101   // function the compiler would have chosen. One function will be preferred
102   // over the other if it is possible to create it without compiler errors,
103   // otherwise the compiler will simply remove it, and default to the less
104   // preferred function.
105   template <typename R>
106   static Yes test(R* r, decltype(r->AddRef(), r->Release(), 42));
107   template <typename C>
108   static No test(...);
109 
110  public:
111   // Trick the compiler to tell if it's possible to call AddRef() and Release().
112   static const bool value = sizeof(test<T>((T*)nullptr, 42)) == sizeof(Yes);
113 };
114 
115 // TernaryTypeOperator is a helper class to select a type based on a static bool
116 // value.
117 template <bool condition, typename IfTrueT, typename IfFalseT>
118 struct TernaryTypeOperator {};
119 
120 template <typename IfTrueT, typename IfFalseT>
121 struct TernaryTypeOperator<true, IfTrueT, IfFalseT> {
122   typedef IfTrueT type;
123 };
124 
125 template <typename IfTrueT, typename IfFalseT>
126 struct TernaryTypeOperator<false, IfTrueT, IfFalseT> {
127   typedef IfFalseT type;
128 };
129 
130 // PointerType<T>::type will be scoped_refptr<T> for ref counted types, and T*
131 // otherwise.
132 template <class T>
133 struct PointerType {
134   typedef typename TernaryTypeOperator<IsRefCounted<T>::value,
135                                        scoped_refptr<T>,
136                                        T*>::type type;
137 };
138 
139 template <typename T>
140 class UnretainedWrapper {
141  public:
142   explicit UnretainedWrapper(T* o) : ptr_(o) {}
143   T* get() const { return ptr_; }
144 
145  private:
146   T* ptr_;
147 };
148 
149 }  // namespace detail
150 
151 template <typename T>
152 static inline detail::UnretainedWrapper<T> Unretained(T* o) {
153   return detail::UnretainedWrapper<T>(o);
154 }
155 
156 template <class ObjectT, class MethodT, class R, typename... Args>
157 class MethodFunctor {
158  public:
159   MethodFunctor(MethodT method, ObjectT* object, Args... args)
160       : method_(method), object_(object), args_(args...) {}
161   R operator()() const {
162     return CallMethod(std::index_sequence_for<Args...>());
163   }
164 
165  private:
166   template <size_t... S>
167   R CallMethod(std::index_sequence<S...>) const {
168     return (object_->*method_)(std::get<S>(args_)...);
169   }
170 
171   MethodT method_;
172   typename detail::PointerType<ObjectT>::type object_;
173   typename std::tuple<typename std::remove_reference<Args>::type...> args_;
174 };
175 
176 template <class ObjectT, class MethodT, class R, typename... Args>
177 class UnretainedMethodFunctor {
178  public:
179   UnretainedMethodFunctor(MethodT method,
180                           detail::UnretainedWrapper<ObjectT> object,
181                           Args... args)
182       : method_(method), object_(object.get()), args_(args...) {}
183   R operator()() const {
184     return CallMethod(std::index_sequence_for<Args...>());
185   }
186 
187  private:
188   template <size_t... S>
189   R CallMethod(std::index_sequence<S...>) const {
190     return (object_->*method_)(std::get<S>(args_)...);
191   }
192 
193   MethodT method_;
194   ObjectT* object_;
195   typename std::tuple<typename std::remove_reference<Args>::type...> args_;
196 };
197 
198 template <class FunctorT, class R, typename... Args>
199 class Functor {
200  public:
201   Functor(const FunctorT& functor, Args... args)
202       : functor_(functor), args_(args...) {}
203   R operator()() const {
204     return CallFunction(std::index_sequence_for<Args...>());
205   }
206 
207  private:
208   template <size_t... S>
209   R CallFunction(std::index_sequence<S...>) const {
210     return functor_(std::get<S>(args_)...);
211   }
212 
213   FunctorT functor_;
214   typename std::tuple<typename std::remove_reference<Args>::type...> args_;
215 };
216 
217 #define FP_T(x) R (ObjectT::*x)(Args...)
218 
219 template <class ObjectT, class R, typename... Args>
220 MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
221     FP_T(method),
222     ObjectT* object,
223     typename detail::identity<Args>::type... args) {
224   return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object,
225                                                           args...);
226 }
227 
228 template <class ObjectT, class R, typename... Args>
229 MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
230     FP_T(method),
231     const scoped_refptr<ObjectT>& object,
232     typename detail::identity<Args>::type... args) {
233   return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object.get(),
234                                                           args...);
235 }
236 
237 template <class ObjectT, class R, typename... Args>
238 UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
239     FP_T(method),
240     detail::UnretainedWrapper<ObjectT> object,
241     typename detail::identity<Args>::type... args) {
242   return UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(
243       method, object, args...);
244 }
245 
246 #undef FP_T
247 #define FP_T(x) R (ObjectT::*x)(Args...) const
248 
249 template <class ObjectT, class R, typename... Args>
250 MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
251     FP_T(method),
252     const ObjectT* object,
253     typename detail::identity<Args>::type... args) {
254   return MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(method, object,
255                                                                 args...);
256 }
257 template <class ObjectT, class R, typename... Args>
258 UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
259     FP_T(method),
260     detail::UnretainedWrapper<const ObjectT> object,
261     typename detail::identity<Args>::type... args) {
262   return UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(
263       method, object, args...);
264 }
265 
266 #undef FP_T
267 #define FP_T(x) R (*x)(Args...)
268 
269 template <class R, typename... Args>
270 Functor<FP_T(NONAME), R, Args...> Bind(
271     FP_T(function),
272     typename detail::identity<Args>::type... args) {
273   return Functor<FP_T(NONAME), R, Args...>(function, args...);
274 }
275 
276 #undef FP_T
277 
278 }  // namespace rtc
279 
280 #undef NONAME
281 
282 #endif  // RTC_BASE_BIND_H_
283