blob: 16ac556b467a75dd351656dbf42988200d7158fd [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 Bonadeid9708072019-01-25 20:26:48 +010067#include "api/scoped_refptr.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020068#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.
Yves Gerey665174f2018-06-19 15:03:05 +020080template <class T>
81struct identity {
82 typedef T type;
83};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084
85// IsRefCounted<T>::value will be true for types that can be used in
86// rtc::scoped_refptr<T>, i.e. types that implements nullary functions AddRef()
87// and Release(), regardless of their return types. AddRef() and Release() can
88// be defined in T or any superclass of T.
89template <typename T>
90class IsRefCounted {
91 // This is a complex implementation detail done with SFINAE.
92
93 // Define types such that sizeof(Yes) != sizeof(No).
Yves Gerey665174f2018-06-19 15:03:05 +020094 struct Yes {
95 char dummy[1];
96 };
97 struct No {
98 char dummy[2];
99 };
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200100 // Define two overloaded template functions with return types of different
101 // size. This way, we can use sizeof() on the return type to determine which
102 // function the compiler would have chosen. One function will be preferred
103 // over the other if it is possible to create it without compiler errors,
104 // otherwise the compiler will simply remove it, and default to the less
105 // preferred function.
106 template <typename R>
107 static Yes test(R* r, decltype(r->AddRef(), r->Release(), 42));
Yves Gerey665174f2018-06-19 15:03:05 +0200108 template <typename C>
109 static No test(...);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200110
Yves Gerey665174f2018-06-19 15:03:05 +0200111 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200112 // Trick the compiler to tell if it's possible to call AddRef() and Release().
113 static const bool value = sizeof(test<T>((T*)nullptr, 42)) == sizeof(Yes);
114};
115
116// TernaryTypeOperator is a helper class to select a type based on a static bool
117// value.
118template <bool condition, typename IfTrueT, typename IfFalseT>
119struct TernaryTypeOperator {};
120
121template <typename IfTrueT, typename IfFalseT>
122struct TernaryTypeOperator<true, IfTrueT, IfFalseT> {
123 typedef IfTrueT type;
124};
125
126template <typename IfTrueT, typename IfFalseT>
127struct TernaryTypeOperator<false, IfTrueT, IfFalseT> {
128 typedef IfFalseT type;
129};
130
131// PointerType<T>::type will be scoped_refptr<T> for ref counted types, and T*
132// otherwise.
133template <class T>
134struct PointerType {
135 typedef typename TernaryTypeOperator<IsRefCounted<T>::value,
136 scoped_refptr<T>,
137 T*>::type type;
138};
139
140template <typename T>
141class UnretainedWrapper {
142 public:
143 explicit UnretainedWrapper(T* o) : ptr_(o) {}
144 T* get() const { return ptr_; }
145
146 private:
147 T* ptr_;
148};
149
150} // namespace detail
151
152template <typename T>
153static inline detail::UnretainedWrapper<T> Unretained(T* o) {
154 return detail::UnretainedWrapper<T>(o);
155}
156
157template <class ObjectT, class MethodT, class R, typename... Args>
158class MethodFunctor {
159 public:
160 MethodFunctor(MethodT method, ObjectT* object, Args... args)
161 : method_(method), object_(object), args_(args...) {}
162 R operator()() const {
163 return CallMethod(typename sequence_generator<sizeof...(Args)>::type());
164 }
165
166 private:
167 // Use sequence_generator (see template_util.h) to expand a MethodFunctor
168 // with 2 arguments to (std::get<0>(args_), std::get<1>(args_)), for
169 // instance.
170 template <int... S>
171 R CallMethod(sequence<S...>) const {
172 return (object_->*method_)(std::get<S>(args_)...);
173 }
174
175 MethodT method_;
176 typename detail::PointerType<ObjectT>::type object_;
177 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
178};
179
180template <class ObjectT, class MethodT, class R, typename... Args>
181class UnretainedMethodFunctor {
182 public:
183 UnretainedMethodFunctor(MethodT method,
184 detail::UnretainedWrapper<ObjectT> object,
185 Args... args)
186 : method_(method), object_(object.get()), args_(args...) {}
187 R operator()() const {
188 return CallMethod(typename sequence_generator<sizeof...(Args)>::type());
189 }
190
191 private:
192 // Use sequence_generator (see template_util.h) to expand an
193 // UnretainedMethodFunctor with 2 arguments to (std::get<0>(args_),
194 // std::get<1>(args_)), for instance.
195 template <int... S>
196 R CallMethod(sequence<S...>) const {
197 return (object_->*method_)(std::get<S>(args_)...);
198 }
199
200 MethodT method_;
201 ObjectT* object_;
202 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
203};
204
205template <class FunctorT, class R, typename... Args>
206class Functor {
207 public:
208 Functor(const FunctorT& functor, Args... args)
209 : functor_(functor), args_(args...) {}
210 R operator()() const {
211 return CallFunction(typename sequence_generator<sizeof...(Args)>::type());
212 }
213
214 private:
215 // Use sequence_generator (see template_util.h) to expand a Functor
216 // with 2 arguments to (std::get<0>(args_), std::get<1>(args_)), for
217 // instance.
218 template <int... S>
219 R CallFunction(sequence<S...>) const {
220 return functor_(std::get<S>(args_)...);
221 }
222
223 FunctorT functor_;
224 typename std::tuple<typename std::remove_reference<Args>::type...> args_;
225};
226
227#define FP_T(x) R (ObjectT::*x)(Args...)
228
229template <class ObjectT, class R, typename... Args>
230MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
231 FP_T(method),
232 ObjectT* object,
233 typename detail::identity<Args>::type... args) {
234 return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object,
235 args...);
236}
237
238template <class ObjectT, class R, typename... Args>
239MethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
240 FP_T(method),
241 const scoped_refptr<ObjectT>& object,
242 typename detail::identity<Args>::type... args) {
243 return MethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(method, object.get(),
244 args...);
245}
246
247template <class ObjectT, class R, typename... Args>
248UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...> Bind(
249 FP_T(method),
250 detail::UnretainedWrapper<ObjectT> object,
251 typename detail::identity<Args>::type... args) {
252 return UnretainedMethodFunctor<ObjectT, FP_T(NONAME), R, Args...>(
253 method, object, args...);
254}
255
256#undef FP_T
257#define FP_T(x) R (ObjectT::*x)(Args...) const
258
259template <class ObjectT, class R, typename... Args>
260MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
261 FP_T(method),
262 const ObjectT* object,
263 typename detail::identity<Args>::type... args) {
264 return MethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(method, object,
265 args...);
266}
267template <class ObjectT, class R, typename... Args>
268UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...> Bind(
269 FP_T(method),
270 detail::UnretainedWrapper<const ObjectT> object,
271 typename detail::identity<Args>::type... args) {
272 return UnretainedMethodFunctor<const ObjectT, FP_T(NONAME), R, Args...>(
273 method, object, args...);
274}
275
276#undef FP_T
277#define FP_T(x) R (*x)(Args...)
278
279template <class R, typename... Args>
280Functor<FP_T(NONAME), R, Args...> Bind(
281 FP_T(function),
282 typename detail::identity<Args>::type... args) {
283 return Functor<FP_T(NONAME), R, Args...>(function, args...);
284}
285
286#undef FP_T
287
288} // namespace rtc
289
290#undef NONAME
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200292#endif // RTC_BASE_BIND_H_