1 $$ This is a pump file for generating file templates. Pump is a python
2 $$ script that is part of the Google Test suite of utilities. Description
5 $$ http://code.google.com/p/googletest/wiki/PumpManual
8 $$ See comment for MAX_ARITY in base/bind.h.pump.
11 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
12 // Use of this source code is governed by a BSD-style license that can be
13 // found in the LICENSE file.
15 #ifndef BASE_CALLBACK_H_
16 #define BASE_CALLBACK_H_
18 #include "base/callback_forward.h"
19 #include "base/callback_internal.h"
20 #include "base/template_util.h"
22 // NOTE: Header files that do not require the full definition of Callback or
23 // Closure should #include "base/callback_forward.h" instead of this file.
25 // -----------------------------------------------------------------------------
27 // -----------------------------------------------------------------------------
29 // The templated Callback class is a generalized function object. Together
30 // with the Bind() function in bind.h, they provide a type-safe method for
31 // performing partial application of functions.
33 // Partial application (or "currying") is the process of binding a subset of
34 // a function's arguments to produce another function that takes fewer
35 // arguments. This can be used to pass around a unit of delayed execution,
36 // much like lexical closures are used in other languages. For example, it
37 // is used in Chromium code to schedule tasks on different MessageLoops.
39 // A callback with no unbound input parameters (base::Callback<void(void)>)
40 // is called a base::Closure. Note that this is NOT the same as what other
41 // languages refer to as a closure -- it does not retain a reference to its
42 // enclosing environment.
44 // MEMORY MANAGEMENT AND PASSING
46 // The Callback objects themselves should be passed by const-reference, and
47 // stored by copy. They internally store their state via a refcounted class
48 // and thus do not need to be deleted.
50 // The reason to pass via a const-reference is to avoid unnecessary
51 // AddRef/Release pairs to the internal state.
54 // -----------------------------------------------------------------------------
55 // Quick reference for basic stuff
56 // -----------------------------------------------------------------------------
58 // BINDING A BARE FUNCTION
60 // int Return5() { return 5; }
61 // base::Callback<int(void)> func_cb = base::Bind(&Return5);
62 // LOG(INFO) << func_cb.Run(); // Prints 5.
64 // BINDING A CLASS METHOD
66 // The first argument to bind is the member function to call, the second is
67 // the object on which to call it.
69 // class Ref : public base::RefCountedThreadSafe<Ref> {
71 // int Foo() { return 3; }
72 // void PrintBye() { LOG(INFO) << "bye."; }
74 // scoped_refptr<Ref> ref = new Ref();
75 // base::Callback<void(void)> ref_cb = base::Bind(&Ref::Foo, ref);
76 // LOG(INFO) << ref_cb.Run(); // Prints out 3.
78 // By default the object must support RefCounted or you will get a compiler
79 // error. If you're passing between threads, be sure it's
80 // RefCountedThreadSafe! See "Advanced binding of member functions" below if
81 // you don't want to use reference counting.
85 // Callbacks can be run with their "Run" method, which has the same
86 // signature as the template argument to the callback.
88 // void DoSomething(const base::Callback<void(int, std::string)>& callback) {
89 // callback.Run(5, "hello");
92 // Callbacks can be run more than once (they don't get deleted or marked when
93 // run). However, this precludes using base::Passed (see below).
95 // void DoSomething(const base::Callback<double(double)>& callback) {
96 // double myresult = callback.Run(3.14159);
97 // myresult += callback.Run(2.71828);
100 // PASSING UNBOUND INPUT PARAMETERS
102 // Unbound parameters are specified at the time a callback is Run(). They are
103 // specified in the Callback template type:
105 // void MyFunc(int i, const std::string& str) {}
106 // base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
107 // cb.Run(23, "hello, world");
109 // PASSING BOUND INPUT PARAMETERS
111 // Bound parameters are specified when you create thee callback as arguments
112 // to Bind(). They will be passed to the function and the Run()ner of the
113 // callback doesn't see those values or even know that the function it's
116 // void MyFunc(int i, const std::string& str) {}
117 // base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");
120 // A callback with no unbound input parameters (base::Callback<void(void)>)
121 // is called a base::Closure. So we could have also written:
123 // base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
125 // When calling member functions, bound parameters just go after the object
128 // base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
130 // PARTIAL BINDING OF PARAMETERS
132 // You can specify some parameters when you create the callback, and specify
133 // the rest when you execute the callback.
135 // void MyFunc(int i, const std::string& str) {}
136 // base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
137 // cb.Run("hello world");
139 // When calling a function bound parameters are first, followed by unbound
143 // -----------------------------------------------------------------------------
144 // Quick reference for advanced binding
145 // -----------------------------------------------------------------------------
147 // BINDING A CLASS METHOD WITH WEAK POINTERS
149 // base::Bind(&MyClass::Foo, GetWeakPtr());
151 // The callback will not be run if the object has already been destroyed.
152 // DANGER: weak pointers are not threadsafe, so don't use this
153 // when passing between threads!
155 // BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
157 // base::Bind(&MyClass::Foo, base::Unretained(this));
159 // This disables all lifetime management on the object. You're responsible
160 // for making sure the object is alive at the time of the call. You break it,
163 // BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
165 // MyClass* myclass = new MyClass;
166 // base::Bind(&MyClass::Foo, base::Owned(myclass));
168 // The object will be deleted when the callback is destroyed, even if it's
169 // not run (like if you post a task during shutdown). Potentially useful for
170 // "fire and forget" cases.
172 // IGNORING RETURN VALUES
174 // Sometimes you want to call a function that returns a value in a callback
175 // that doesn't expect a return value.
177 // int DoSomething(int arg) { cout << arg << endl; }
178 // base::Callback<void<int>) cb =
179 // base::Bind(base::IgnoreResult(&DoSomething));
182 // -----------------------------------------------------------------------------
183 // Quick reference for binding parameters to Bind()
184 // -----------------------------------------------------------------------------
186 // Bound parameters are specified as arguments to Bind() and are passed to the
187 // function. A callback with no parameters or no unbound parameters is called a
188 // Closure (base::Callback<void(void)> and base::Closure are the same thing).
190 // PASSING PARAMETERS OWNED BY THE CALLBACK
192 // void Foo(int* arg) { cout << *arg << endl; }
193 // int* pn = new int(1);
194 // base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
196 // The parameter will be deleted when the callback is destroyed, even if it's
197 // not run (like if you post a task during shutdown).
199 // PASSING PARAMETERS AS A scoped_ptr
201 // void TakesOwnership(scoped_ptr<Foo> arg) {}
202 // scoped_ptr<Foo> f(new Foo);
203 // // f becomes null during the following call.
204 // base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));
206 // Ownership of the parameter will be with the callback until the it is run,
207 // when ownership is passed to the callback function. This means the callback
208 // can only be run once. If the callback is never run, it will delete the
209 // object when it's destroyed.
211 // PASSING PARAMETERS AS A scoped_refptr
213 // void TakesOneRef(scoped_refptr<Foo> arg) {}
214 // scoped_refptr<Foo> f(new Foo)
215 // base::Closure cb = base::Bind(&TakesOneRef, f);
217 // This should "just work." The closure will take a reference as long as it
218 // is alive, and another reference will be taken for the called function.
220 // PASSING PARAMETERS BY REFERENCE
222 // void foo(int arg) { cout << arg << endl }
224 // base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
226 // has_ref.Run(); // Prints "2"
228 // Normally parameters are copied in the closure. DANGER: ConstRef stores a
229 // const reference instead, referencing the original parameter. This means
230 // that you must ensure the object outlives the callback!
233 // -----------------------------------------------------------------------------
234 // Implementation notes
235 // -----------------------------------------------------------------------------
237 // WHERE IS THIS DESIGN FROM:
239 // The design Callback and Bind is heavily influenced by C++'s
240 // tr1::function/tr1::bind, and by the "Google Callback" system used inside
244 // HOW THE IMPLEMENTATION WORKS:
246 // There are three main components to the system:
247 // 1) The Callback classes.
248 // 2) The Bind() functions.
249 // 3) The arguments wrappers (e.g., Unretained() and ConstRef()).
251 // The Callback classes represent a generic function pointer. Internally,
252 // it stores a refcounted piece of state that represents the target function
253 // and all its bound parameters. Each Callback specialization has a templated
254 // constructor that takes an BindState<>*. In the context of the constructor,
255 // the static type of this BindState<> pointer uniquely identifies the
256 // function it is representing, all its bound parameters, and a Run() method
257 // that is capable of invoking the target.
259 // Callback's constructor takes the BindState<>* that has the full static type
260 // and erases the target function type as well as the types of the bound
261 // parameters. It does this by storing a pointer to the specific Run()
262 // function, and upcasting the state of BindState<>* to a
263 // BindStateBase*. This is safe as long as this BindStateBase pointer
264 // is only used with the stored Run() pointer.
266 // To BindState<> objects are created inside the Bind() functions.
267 // These functions, along with a set of internal templates, are responsible for
269 // - Unwrapping the function signature into return type, and parameters
270 // - Determining the number of parameters that are bound
271 // - Creating the BindState storing the bound parameters
272 // - Performing compile-time asserts to avoid error-prone behavior
273 // - Returning an Callback<> with an arity matching the number of unbound
274 // parameters and that knows the correct refcounting semantics for the
275 // target object if we are binding a method.
277 // The Bind functions do the above using type-inference, and template
280 // By default Bind() will store copies of all bound parameters, and attempt
281 // to refcount a target object if the function being bound is a class method.
282 // These copies are created even if the function takes parameters as const
283 // references. (Binding to non-const references is forbidden, see bind.h.)
285 // To change this behavior, we introduce a set of argument wrappers
286 // (e.g., Unretained(), and ConstRef()). These are simple container templates
287 // that are passed by value, and wrap a pointer to argument. See the
288 // file-level comment in base/bind_helpers.h for more info.
290 // These types are passed to the Unwrap() functions, and the MaybeRefcount()
291 // functions respectively to modify the behavior of Bind(). The Unwrap()
292 // and MaybeRefcount() functions change behavior by doing partial
293 // specialization based on whether or not a parameter is a wrapper type.
295 // ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.
298 // WHY NOT TR1 FUNCTION/BIND?
300 // Direct use of tr1::function and tr1::bind was considered, but ultimately
301 // rejected because of the number of copy constructors invocations involved
302 // in the binding of arguments during construction, and the forwarding of
303 // arguments during invocation. These copies will no longer be an issue in
304 // C++0x because C++0x will support rvalue reference allowing for the compiler
305 // to avoid these copies. However, waiting for C++0x is not an option.
307 // Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
308 // tr1::bind call itself will invoke a non-trivial copy constructor three times
309 // for each bound parameter. Also, each when passing a tr1::function, each
310 // bound argument will be copied again.
312 // In addition to the copies taken at binding and invocation, copying a
313 // tr1::function causes a copy to be made of all the bound parameters and
316 // Furthermore, in Chromium, it is desirable for the Callback to take a
317 // reference on a target object when representing a class method call. This
318 // is not supported by tr1.
320 // Lastly, tr1::function and tr1::bind has a more general and flexible API.
321 // This includes things like argument reordering by use of
322 // tr1::bind::placeholder, support for non-const reference parameters, and some
323 // limited amount of subtyping of the tr1::function object (e.g.,
324 // tr1::function<int(int)> is convertible to tr1::function<void(int)>).
326 // These are not features that are required in Chromium. Some of them, such as
327 // allowing for reference parameters, and subtyping of functions, may actually
328 // become a source of errors. Removing support for these features actually
329 // allows for a simpler implementation, and a terser Currying API.
332 // WHY NOT GOOGLE CALLBACKS?
334 // The Google callback system also does not support refcounting. Furthermore,
335 // its implementation has a number of strange edge cases with respect to type
336 // conversion of its arguments. In particular, the argument's constness must
337 // at times match exactly the function signature, or the type-inference might
338 // break. Given the above, writing a custom solution was easier.
341 // MISSING FUNCTIONALITY
342 // - Invoking the return of Bind. Bind(&foo).Run() does not work;
343 // - Binding arrays to functions that take a non-const pointer.
345 // void Foo(const char* ptr);
346 // void Bar(char* ptr);
347 // Bind(&Foo, "test");
348 // Bind(&Bar, "test"); // This fails because ptr is not const.
352 // First, we forward declare the Callback class template. This informs the
353 // compiler that the template only has 1 type parameter which is the function
354 // signature that the Callback is representing.
356 // After this, create template specializations for 0-$(MAX_ARITY) parameters. Note that
357 // even though the template typelist grows, the specialization still
358 // only has one type: the function signature.
360 // If you are thinking of forward declaring Callback in your own header file,
361 // please include "base/callback_forward.h" instead.
362 template <typename Sig>
366 template <typename Runnable, typename RunType, typename BoundArgsType>
368 } // namespace internal
371 $range ARITY 0..MAX_ARITY
376 template <typename R>
377 class Callback<R(void)> : public internal::CallbackBase {
379 template <typename R, $for ARG , [[typename A$(ARG)]]>
380 class Callback<R($for ARG , [[A$(ARG)]])> : public internal::CallbackBase {
384 typedef R(RunType)($for ARG , [[A$(ARG)]]);
386 Callback() : CallbackBase(NULL) { }
388 // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
389 // return the exact Callback<> type. See base/bind.h for details.
390 template <typename Runnable, typename BindRunType, typename BoundArgsType>
391 Callback(internal::BindState<Runnable, BindRunType,
392 BoundArgsType>* bind_state)
393 : CallbackBase(bind_state) {
395 // Force the assignment to a local variable of PolymorphicInvoke
396 // so the compiler will typecheck that the passed in Run() method has
398 PolymorphicInvoke invoke_func =
399 &internal::BindState<Runnable, BindRunType, BoundArgsType>
401 polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
404 bool Equals(const Callback& other) const {
405 return CallbackBase::Equals(other);
409 [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType a$(ARG)]]) const {
410 PolymorphicInvoke f =
411 reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
413 return f(bind_state_.get()[[]]
414 $if ARITY != 0 [[, ]]
416 [[internal::CallbackForward(a$(ARG))]]);
420 typedef R(*PolymorphicInvoke)(
421 internal::BindStateBase*[[]]
422 $if ARITY != 0 [[, ]]
423 $for ARG , [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType]]);
430 // Syntactic sugar to make Callback<void(void)> easier to declare since it
431 // will be used in a lot of APIs with delayed execution.
432 typedef Callback<void(void)> Closure;
436 #endif // BASE_CALLBACK_H