blob: b9f98b9dfe9b24922620361738c68661a5778508 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011// Bind() is an overloaded function that converts method calls into function
Magnus Jedvertd3de9c52015-08-20 16:03:52 +020012// 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.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019//
deadbeefccaaffb2017-02-25 12:56:20 -080020// 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//
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024// 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// }
Magnus Jedvertd3de9c52015-08-20 16:03:52 +020039//
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.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070048// invoker.AsyncInvoke(RTC_FROM_HERE,rtc::Bind(&Bar::Test, this));
Magnus Jedvertd3de9c52015-08-20 16:03:52 +020049// }
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//
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020061#ifndef RTC_BASE_BIND_H_
62#define RTC_BASE_BIND_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020064#include <tuple>
65#include <type_traits>
deadbeef08187d42017-02-25 11:21:18 -080066
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "rtc_base/scoped_ref_ptr.h"
68#include "rtc_base/template_util.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020069
70#define NONAME
71
72namespace rtc {
73namespace detail {
74// This is needed because the template parameters in Bind can't be resolved
75// if they're used both as parameters of the function pointer type and as
76// parameters to Bind itself: the function pointer parameters are exact
77// matches to the function prototype, but the parameters to bind have
78// references stripped. This trick allows the compiler to dictate the Bind
79// parameter types rather than deduce them.
80template <class T> struct identity { typedef T type; };
81
82// IsRefCounted<T>::value will be true for types that can be used in
83// rtc::scoped_refptr<T>, i.e. types that implements nullary functions AddRef()
84// and Release(), regardless of their return types. AddRef() and Release() can
85// be defined in T or any superclass of T.
86template <typename T>
87class IsRefCounted {
88 // This is a complex implementation detail done with SFINAE.
89
90 // Define types such that sizeof(Yes) != sizeof(No).
91 struct Yes { char dummy[1]; };
92 struct No { char dummy[2]; };
93 // Define two overloaded template functions with return types of different
94 // size. This way, we can use sizeof() on the return type to determine which
95 // function the compiler would have chosen. One function will be preferred
96 // over the other if it is possible to create it without compiler errors,
97 // otherwise the compiler will simply remove it, and default to the less
98 // preferred function.
99 template <typename R>
100 static Yes test(R* r, decltype(r->AddRef(), r->Release(), 42));
101 template <typename C> static No test(...);
102
103public:
104 // Trick the compiler to tell if it's possible to call AddRef() and Release().
105 static const bool value = sizeof(test<T>((T*)nullptr, 42)) == sizeof(Yes);
106};
107
108// TernaryTypeOperator is a helper class to select a type based on a static bool
109// value.
110template <bool condition, typename IfTrueT, typename IfFalseT>
111struct TernaryTypeOperator {};
112
113template <typename IfTrueT, typename IfFalseT>
114struct TernaryTypeOperator<true, IfTrueT, IfFalseT> {
115 typedef IfTrueT type;
116};
117
118template <typename IfTrueT, typename IfFalseT>
119struct TernaryTypeOperator<false, IfTrueT, IfFalseT> {
120 typedef IfFalseT type;
121};
122
123// PointerType<T>::type will be scoped_refptr<T> for ref counted types, and T*
124// otherwise.
125template <class T>
126struct PointerType {
127 typedef typename TernaryTypeOperator<IsRefCounted<T>::value,
128 scoped_refptr<T>,
129 T*>::type type;
130};
131
132template <typename T>
133class UnretainedWrapper {
134 public:
135 explicit UnretainedWrapper(T* o) : ptr_(o) {}
136 T* get() const { return ptr_; }
137
138 private:
139 T* ptr_;
140};
141
142} // namespace detail
143
144template <typename T>
145static inline detail::UnretainedWrapper<T> Unretained(T* o) {
146 return detail::UnretainedWrapper<T>(o);
147}
148
149template <class ObjectT, class MethodT, class R, typename... Args>
150class MethodFunctor {
151 public:
152 MethodFunctor(MethodT method, ObjectT* object, Args... args)
153 : method_(method), object_(object), args_(args...) {}
154 R operator()() const {
155 return CallMethod(typename sequence_generator<sizeof...(Args)>::type());
156 }
157
158 private:
159 // Use sequence_generator (see template_util.h) to expand a MethodFunctor
160 // with 2 arguments to (std::get<0>(args_), std::get<1>(args_)), for
161 // instance.
162 template <int... S>
163 R CallMethod(sequence<S...>) const {
164 return (object_->*method_)(std::get<S>(args_)...);
165 }
166
167 MethodT method_;
168 typename detail::PointerType<ObjectT>::type object_;
169 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
170};
171
172template <class ObjectT, class MethodT, class R, typename... Args>
173class UnretainedMethodFunctor {
174 public:
175 UnretainedMethodFunctor(MethodT method,
176 detail::UnretainedWrapper<ObjectT> object,
177 Args... args)
178 : method_(method), object_(object.get()), args_(args...) {}
179 R operator()() const {
180 return CallMethod(typename sequence_generator<sizeof...(Args)>::type());
181 }
182
183 private:
184 // Use sequence_generator (see template_util.h) to expand an
185 // UnretainedMethodFunctor with 2 arguments to (std::get<0>(args_),
186 // std::get<1>(args_)), for instance.
187 template <int... S>
188 R CallMethod(sequence<S...>) const {
189 return (object_->*method_)(std::get<S>(args_)...);
190 }
191
192 MethodT method_;
193 ObjectT* object_;
194 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
195};
196
197template <class FunctorT, class R, typename... Args>
198class Functor {
199 public:
200 Functor(const FunctorT& functor, Args... args)
201 : functor_(functor), args_(args...) {}
202 R operator()() const {
203 return CallFunction(typename sequence_generator<sizeof...(Args)>::type());
204 }
205
206 private:
207 // Use sequence_generator (see template_util.h) to expand a Functor
208 // with 2 arguments to (std::get<0>(args_), std::get<1>(args_)), for
209 // instance.
210 template <int... S>
211 R CallFunction(sequence<S...>) const {
212 return functor_(std::get<S>(args_)...);
213 }
214
215 FunctorT functor_;
216 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
217};
218
219#define FP_T(x) R (ObjectT::*x)(Args...)
220
221template <class ObjectT, class R, typename... Args>
222MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
223 FP_T(method),
224 ObjectT* object,
225 typename detail::identity<Args>::type... args) {
226 return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object,
227 args...);
228}
229
230template <class ObjectT, class R, typename... Args>
231MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
232 FP_T(method),
233 const scoped_refptr<ObjectT>& object,
234 typename detail::identity<Args>::type... args) {
235 return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object.get(),
236 args...);
237}
238
239template <class ObjectT, class R, typename... Args>
240UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
241 FP_T(method),
242 detail::UnretainedWrapper<ObjectT> object,
243 typename detail::identity<Args>::type... args) {
244 return UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(
245 method, object, args...);
246}
247
248#undef FP_T
249#define FP_T(x) R (ObjectT::*x)(Args...) const
250
251template <class ObjectT, class R, typename... Args>
252MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
253 FP_T(method),
254 const ObjectT* object,
255 typename detail::identity<Args>::type... args) {
256 return MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(method, object,
257 args...);
258}
259template <class ObjectT, class R, typename... Args>
260UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
261 FP_T(method),
262 detail::UnretainedWrapper<const ObjectT> object,
263 typename detail::identity<Args>::type... args) {
264 return UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(
265 method, object, args...);
266}
267
268#undef FP_T
269#define FP_T(x) R (*x)(Args...)
270
271template <class R, typename... Args>
272Functor<FP_T(NONAME), R, Args...> Bind(
273 FP_T(function),
274 typename detail::identity<Args>::type... args) {
275 return Functor<FP_T(NONAME), R, Args...>(function, args...);
276}
277
278#undef FP_T
279
280} // namespace rtc
281
282#undef NONAME
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200284#endif // RTC_BASE_BIND_H_