blob: b61d189f7a573e75789777488f6b5700307a6ece [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"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020068
69#define NONAME
70
71namespace rtc {
72namespace 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.
Yves Gerey665174f2018-06-19 15:03:05 +020079template <class T>
80struct identity {
81 typedef T type;
82};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020083
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.
88template <typename T>
89class IsRefCounted {
90 // This is a complex implementation detail done with SFINAE.
91
92 // Define types such that sizeof(Yes) != sizeof(No).
Yves Gerey665174f2018-06-19 15:03:05 +020093 struct Yes {
94 char dummy[1];
95 };
96 struct No {
97 char dummy[2];
98 };
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020099 // 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));
Yves Gerey665174f2018-06-19 15:03:05 +0200107 template <typename C>
108 static No test(...);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200109
Yves Gerey665174f2018-06-19 15:03:05 +0200110 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 // 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.
117template <bool condition, typename IfTrueT, typename IfFalseT>
118struct TernaryTypeOperator {};
119
120template <typename IfTrueT, typename IfFalseT>
121struct TernaryTypeOperator<true, IfTrueT, IfFalseT> {
122 typedef IfTrueT type;
123};
124
125template <typename IfTrueT, typename IfFalseT>
126struct 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.
132template <class T>
133struct PointerType {
134 typedef typename TernaryTypeOperator<IsRefCounted<T>::value,
135 scoped_refptr<T>,
136 T*>::type type;
137};
138
139template <typename T>
140class 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
151template <typename T>
152static inline detail::UnretainedWrapper<T> Unretained(T* o) {
153 return detail::UnretainedWrapper<T>(o);
154}
155
156template <class ObjectT, class MethodT, class R, typename... Args>
157class MethodFunctor {
158 public:
159 MethodFunctor(MethodT method, ObjectT* object, Args... args)
160 : method_(method), object_(object), args_(args...) {}
161 R operator()() const {
Steve Antone1611a02019-11-27 10:53:45 -0800162 return CallMethod(std::index_sequence_for<Args...>());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200163 }
164
165 private:
Steve Antone1611a02019-11-27 10:53:45 -0800166 template <size_t... S>
167 R CallMethod(std::index_sequence<S...>) const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200168 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
176template <class ObjectT, class MethodT, class R, typename... Args>
177class 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 {
Steve Antone1611a02019-11-27 10:53:45 -0800184 return CallMethod(std::index_sequence_for<Args...>());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185 }
186
187 private:
Steve Antone1611a02019-11-27 10:53:45 -0800188 template <size_t... S>
189 R CallMethod(std::index_sequence<S...>) const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200190 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
198template <class FunctorT, class R, typename... Args>
199class Functor {
200 public:
201 Functor(const FunctorT& functor, Args... args)
202 : functor_(functor), args_(args...) {}
203 R operator()() const {
Steve Antone1611a02019-11-27 10:53:45 -0800204 return CallFunction(std::index_sequence_for<Args...>());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200205 }
206
207 private:
Steve Antone1611a02019-11-27 10:53:45 -0800208 template <size_t... S>
209 R CallFunction(std::index_sequence<S...>) const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200210 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
219template <class ObjectT, class R, typename... Args>
220MethodFunctor<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
228template <class ObjectT, class R, typename... Args>
229MethodFunctor<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
237template <class ObjectT, class R, typename... Args>
238UnretainedMethodFunctor<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
249template <class ObjectT, class R, typename... Args>
250MethodFunctor<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}
257template <class ObjectT, class R, typename... Args>
258UnretainedMethodFunctor<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
269template <class R, typename... Args>
270Functor<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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200282#endif // RTC_BASE_BIND_H_