blob: 686196dae6a619d6748ffeecb514eace046711aa [file] [log] [blame]
ajwong@chromium.orge2cca632011-02-15 10:27:38 +09001$$ 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
3$$ can be found here:
4$$
5$$ http://code.google.com/p/googletest/wiki/PumpManual
6$$
7
ajwong@chromium.org6f015bd2011-11-29 07:13:54 +09008$$ See comment for MAX_ARITY in base/bind.h.pump.
9$var MAX_ARITY = 7
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090010
ajwong@chromium.org22a8a0d2012-01-04 09:57:39 +090011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090012// Use of this source code is governed by a BSD-style license that can be
13// found in the LICENSE file.
14
15#ifndef BASE_CALLBACK_H_
16#define BASE_CALLBACK_H_
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090017
erikwright@chromium.orgac2a1882011-12-08 06:44:06 +090018#include "base/callback_forward.h"
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090019#include "base/callback_internal.h"
ajwong@chromium.orgec1750a2011-06-27 01:22:50 +090020#include "base/template_util.h"
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090021
erikwright@chromium.orgac2a1882011-12-08 06:44:06 +090022// 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.
24
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090025// -----------------------------------------------------------------------------
26// Introduction
27// -----------------------------------------------------------------------------
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090028//
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
dubroy@chromium.org43d9ac32012-12-07 04:00:50 +090031// performing partial application of functions.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090032//
dubroy@chromium.org43d9ac32012-12-07 04:00:50 +090033// 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090038//
dubroy@chromium.org43d9ac32012-12-07 04:00:50 +090039// 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090043//
44// MEMORY MANAGEMENT AND PASSING
45//
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.
49//
50// The reason to pass via a const-reference is to avoid unnecessary
51// AddRef/Release pairs to the internal state.
52//
53//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090054// -----------------------------------------------------------------------------
55// Quick reference for basic stuff
56// -----------------------------------------------------------------------------
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090057//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090058// BINDING A BARE FUNCTION
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090059//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090060// int Return5() { return 5; }
61// base::Callback<int(void)> func_cb = base::Bind(&Return5);
62// LOG(INFO) << func_cb.Run(); // Prints 5.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090063//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090064// BINDING A CLASS METHOD
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090065//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090066// The first argument to bind is the member function to call, the second is
67// the object on which to call it.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090068//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090069// class Ref : public base::RefCountedThreadSafe<Ref> {
70// public:
71// int Foo() { return 3; }
72// void PrintBye() { LOG(INFO) << "bye."; }
73// };
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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090077//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090078// 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090082//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090083// RUNNING A CALLBACK
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090084//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090085// Callbacks can be run with their "Run" method, which has the same
86// signature as the template argument to the callback.
ajwong@chromium.org97d22e32011-05-19 05:21:12 +090087//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090088// void DoSomething(const base::Callback<void(int, std::string)>& callback) {
89// callback.Run(5, "hello");
90// }
ajwong@chromium.org97d22e32011-05-19 05:21:12 +090091//
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +090092// 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).
94//
95// void DoSomething(const base::Callback<double(double)>& callback) {
96// double myresult = callback.Run(3.14159);
97// myresult += callback.Run(2.71828);
98// }
99//
100// PASSING UNBOUND INPUT PARAMETERS
101//
102// Unbound parameters are specified at the time a callback is Run(). They are
103// specified in the Callback template type:
104//
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");
108//
109// PASSING BOUND INPUT PARAMETERS
110//
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
114// calling.
115//
116// void MyFunc(int i, const std::string& str) {}
117// base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");
118// cb.Run();
119//
120// A callback with no unbound input parameters (base::Callback<void(void)>)
121// is called a base::Closure. So we could have also written:
122//
123// base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
124//
125// When calling member functions, bound parameters just go after the object
126// pointer.
127//
128// base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
129//
130// PARTIAL BINDING OF PARAMETERS
131//
132// You can specify some parameters when you create the callback, and specify
133// the rest when you execute the callback.
134//
135// void MyFunc(int i, const std::string& str) {}
xiaomings@google.comdcfad552012-08-14 08:11:50 +0900136// base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +0900137// cb.Run("hello world");
138//
139// When calling a function bound parameters are first, followed by unbound
140// parameters.
141//
142//
143// -----------------------------------------------------------------------------
144// Quick reference for advanced binding
145// -----------------------------------------------------------------------------
146//
147// BINDING A CLASS METHOD WITH WEAK POINTERS
148//
149// base::Bind(&MyClass::Foo, GetWeakPtr());
150//
brandonsalmon@chromium.orgacaaae72014-06-26 15:07:45 +0900151// 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
brettw@chromium.org11e3bfd2012-07-13 05:06:40 +0900153// when passing between threads!
154//
155// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
156//
157// base::Bind(&MyClass::Foo, base::Unretained(this));
158//
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,
161// you own it!
162//
163// BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
164//
165// MyClass* myclass = new MyClass;
166// base::Bind(&MyClass::Foo, base::Owned(myclass));
167//
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.
171//
172// IGNORING RETURN VALUES
173//
174// Sometimes you want to call a function that returns a value in a callback
175// that doesn't expect a return value.
176//
177// int DoSomething(int arg) { cout << arg << endl; }
178// base::Callback<void<int>) cb =
179// base::Bind(base::IgnoreResult(&DoSomething));
180//
181//
182// -----------------------------------------------------------------------------
183// Quick reference for binding parameters to Bind()
184// -----------------------------------------------------------------------------
185//
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).
189//
190// PASSING PARAMETERS OWNED BY THE CALLBACK
191//
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));
195//
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).
198//
199// PASSING PARAMETERS AS A scoped_ptr
200//
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));
205//
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.
210//
211// PASSING PARAMETERS AS A scoped_refptr
212//
213// void TakesOneRef(scoped_refptr<Foo> arg) {}
214// scoped_refptr<Foo> f(new Foo)
215// base::Closure cb = base::Bind(&TakesOneRef, f);
216//
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.
219//
220// PASSING PARAMETERS BY REFERENCE
221//
222// void foo(int arg) { cout << arg << endl }
223// int n = 1;
224// base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
225// n = 2;
226// has_ref.Run(); // Prints "2"
227//
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!
231//
232//
233// -----------------------------------------------------------------------------
234// Implementation notes
235// -----------------------------------------------------------------------------
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900236//
237// WHERE IS THIS DESIGN FROM:
238//
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
241// Google.
242//
243//
244// HOW THE IMPLEMENTATION WORKS:
245//
246// There are three main components to the system:
247// 1) The Callback classes.
248// 2) The Bind() functions.
jhawkins@chromium.orgbb87d2a2011-12-13 09:06:28 +0900249// 3) The arguments wrappers (e.g., Unretained() and ConstRef()).
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900250//
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
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900254// 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900258//
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900259// 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900265//
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900266// To BindState<> objects are created inside the Bind() functions.
267// These functions, along with a set of internal templates, are responsible for
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900268//
269// - Unwrapping the function signature into return type, and parameters
270// - Determining the number of parameters that are bound
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900271// - Creating the BindState storing the bound parameters
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900272// - Performing compile-time asserts to avoid error-prone behavior
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900273// - 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.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900276//
277// The Bind functions do the above using type-inference, and template
278// specializations.
279//
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.
dubroy@chromium.org43d9ac32012-12-07 04:00:50 +0900282// These copies are created even if the function takes parameters as const
283// references. (Binding to non-const references is forbidden, see bind.h.)
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900284//
285// To change this behavior, we introduce a set of argument wrappers
jhawkins@chromium.orgbb87d2a2011-12-13 09:06:28 +0900286// (e.g., Unretained(), and ConstRef()). These are simple container templates
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900287// 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.
289//
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.
294//
295// ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.
296//
297//
298// WHY NOT TR1 FUNCTION/BIND?
299//
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.
306//
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.
311//
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
314// state.
315//
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.
319//
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
jhawkins@chromium.orgbb87d2a2011-12-13 09:06:28 +0900323// limited amount of subtyping of the tr1::function object (e.g.,
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900324// tr1::function<int(int)> is convertible to tr1::function<void(int)>).
325//
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
ajwong@chromium.orgc711b822011-05-17 07:35:14 +0900328// become a source of errors. Removing support for these features actually
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900329// allows for a simpler implementation, and a terser Currying API.
330//
331//
332// WHY NOT GOOGLE CALLBACKS?
333//
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.
339//
340//
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.
344// Example:
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.
349
350namespace base {
351
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.
355//
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.
erikwright@chromium.orgac2a1882011-12-08 06:44:06 +0900359//
360// If you are thinking of forward declaring Callback in your own header file,
361// please include "base/callback_forward.h" instead.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900362template <typename Sig>
363class Callback;
364
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900365namespace internal {
366template <typename Runnable, typename RunType, typename BoundArgsType>
367struct BindState;
368} // namespace internal
369
ajwong@chromium.orge0648232011-02-19 09:52:15 +0900370
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900371$range ARITY 0..MAX_ARITY
372$for ARITY [[
373$range ARG 1..ARITY
374
375$if ARITY == 0 [[
376template <typename R>
ajwong@chromium.org62fb0a02011-02-18 13:05:14 +0900377class Callback<R(void)> : public internal::CallbackBase {
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900378]] $else [[
379template <typename R, $for ARG , [[typename A$(ARG)]]>
ajwong@chromium.org62fb0a02011-02-18 13:05:14 +0900380class Callback<R($for ARG , [[A$(ARG)]])> : public internal::CallbackBase {
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900381]]
382
383 public:
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900384 typedef R(RunType)($for ARG , [[A$(ARG)]]);
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900385
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900386 Callback() : CallbackBase(NULL) { }
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900387
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900388 // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
389 // return the exact Callback<> type. See base/bind.h for details.
xiaomings@google.comdcfad552012-08-14 08:11:50 +0900390 template <typename Runnable, typename BindRunType, typename BoundArgsType>
391 Callback(internal::BindState<Runnable, BindRunType,
392 BoundArgsType>* bind_state)
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900393 : CallbackBase(bind_state) {
394
395 // Force the assignment to a local variable of PolymorphicInvoke
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900396 // so the compiler will typecheck that the passed in Run() method has
397 // the correct type.
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900398 PolymorphicInvoke invoke_func =
xiaomings@google.comdcfad552012-08-14 08:11:50 +0900399 &internal::BindState<Runnable, BindRunType, BoundArgsType>
ajwong@chromium.orgabd70002011-12-20 09:10:04 +0900400 ::InvokerType::Run;
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900401 polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900402 }
403
ajwong@chromium.org3bc50ce2011-09-10 12:14:35 +0900404 bool Equals(const Callback& other) const {
405 return CallbackBase::Equals(other);
406 }
407
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900408 R Run($for ARG ,
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900409 [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType a$(ARG)]]) const {
ajwong@chromium.org62fb0a02011-02-18 13:05:14 +0900410 PolymorphicInvoke f =
411 reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900412
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900413 return f(bind_state_.get()[[]]
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900414$if ARITY != 0 [[, ]]
415$for ARG ,
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +0900416 [[internal::CallbackForward(a$(ARG))]]);
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900417 }
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900418
419 private:
420 typedef R(*PolymorphicInvoke)(
421 internal::BindStateBase*[[]]
422$if ARITY != 0 [[, ]]
423$for ARG , [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType]]);
424
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900425};
426
427
428]] $$ for ARITY
429
wtc@chromium.org98eec042014-07-03 15:10:13 +0900430// Syntactic sugar to make Callback<void(void)> easier to declare since it
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900431// will be used in a lot of APIs with delayed execution.
432typedef Callback<void(void)> Closure;
433
434} // namespace base
435
436#endif // BASE_CALLBACK_H