blob: 00669dd83d1c2dbb518134f0243fd5dbec104133 [file] [log] [blame]
[email protected]ac4c6682012-01-04 00:57:391// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]2041cf342010-02-19 03:15:592// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_CALLBACK_H_
6#define BASE_CALLBACK_H_
7
[email protected]d7f75242011-12-07 21:44:068#include "base/callback_forward.h"
[email protected]59eff912011-02-18 23:29:319#include "base/callback_internal.h"
[email protected]6a341fb2011-06-26 16:22:5010#include "base/template_util.h"
[email protected]2041cf342010-02-19 03:15:5911
[email protected]d7f75242011-12-07 21:44:0612// NOTE: Header files that do not require the full definition of Callback or
13// Closure should #include "base/callback_forward.h" instead of this file.
14
[email protected]24292642012-07-12 20:06:4015// -----------------------------------------------------------------------------
16// Introduction
17// -----------------------------------------------------------------------------
[email protected]2041cf342010-02-19 03:15:5918//
[email protected]b38d3572011-02-15 01:27:3819// The templated Callback class is a generalized function object. Together
20// with the Bind() function in bind.h, they provide a type-safe method for
[email protected]68639bbe2012-12-06 19:00:5021// performing partial application of functions.
[email protected]2041cf342010-02-19 03:15:5922//
[email protected]68639bbe2012-12-06 19:00:5023// Partial application (or "currying") is the process of binding a subset of
24// a function's arguments to produce another function that takes fewer
25// arguments. This can be used to pass around a unit of delayed execution,
26// much like lexical closures are used in other languages. For example, it
27// is used in Chromium code to schedule tasks on different MessageLoops.
[email protected]2041cf342010-02-19 03:15:5928//
[email protected]68639bbe2012-12-06 19:00:5029// A callback with no unbound input parameters (base::Callback<void(void)>)
30// is called a base::Closure. Note that this is NOT the same as what other
31// languages refer to as a closure -- it does not retain a reference to its
32// enclosing environment.
[email protected]2041cf342010-02-19 03:15:5933//
[email protected]b38d3572011-02-15 01:27:3834// MEMORY MANAGEMENT AND PASSING
[email protected]2041cf342010-02-19 03:15:5935//
[email protected]b38d3572011-02-15 01:27:3836// The Callback objects themselves should be passed by const-reference, and
37// stored by copy. They internally store their state via a refcounted class
38// and thus do not need to be deleted.
[email protected]2041cf342010-02-19 03:15:5939//
[email protected]b38d3572011-02-15 01:27:3840// The reason to pass via a const-reference is to avoid unnecessary
41// AddRef/Release pairs to the internal state.
42//
43//
[email protected]24292642012-07-12 20:06:4044// -----------------------------------------------------------------------------
45// Quick reference for basic stuff
46// -----------------------------------------------------------------------------
[email protected]b38d3572011-02-15 01:27:3847//
[email protected]24292642012-07-12 20:06:4048// BINDING A BARE FUNCTION
[email protected]b38d3572011-02-15 01:27:3849//
[email protected]24292642012-07-12 20:06:4050// int Return5() { return 5; }
51// base::Callback<int(void)> func_cb = base::Bind(&Return5);
52// LOG(INFO) << func_cb.Run(); // Prints 5.
[email protected]b38d3572011-02-15 01:27:3853//
[email protected]24292642012-07-12 20:06:4054// BINDING A CLASS METHOD
[email protected]b38d3572011-02-15 01:27:3855//
[email protected]24292642012-07-12 20:06:4056// The first argument to bind is the member function to call, the second is
57// the object on which to call it.
[email protected]b38d3572011-02-15 01:27:3858//
[email protected]24292642012-07-12 20:06:4059// class Ref : public base::RefCountedThreadSafe<Ref> {
60// public:
61// int Foo() { return 3; }
62// void PrintBye() { LOG(INFO) << "bye."; }
63// };
64// scoped_refptr<Ref> ref = new Ref();
65// base::Callback<void(void)> ref_cb = base::Bind(&Ref::Foo, ref);
66// LOG(INFO) << ref_cb.Run(); // Prints out 3.
[email protected]b38d3572011-02-15 01:27:3867//
[email protected]24292642012-07-12 20:06:4068// By default the object must support RefCounted or you will get a compiler
69// error. If you're passing between threads, be sure it's
70// RefCountedThreadSafe! See "Advanced binding of member functions" below if
71// you don't want to use reference counting.
[email protected]b38d3572011-02-15 01:27:3872//
[email protected]24292642012-07-12 20:06:4073// RUNNING A CALLBACK
[email protected]b38d3572011-02-15 01:27:3874//
[email protected]24292642012-07-12 20:06:4075// Callbacks can be run with their "Run" method, which has the same
76// signature as the template argument to the callback.
[email protected]965e00d2011-05-18 20:21:1277//
[email protected]24292642012-07-12 20:06:4078// void DoSomething(const base::Callback<void(int, std::string)>& callback) {
79// callback.Run(5, "hello");
80// }
[email protected]965e00d2011-05-18 20:21:1281//
[email protected]24292642012-07-12 20:06:4082// Callbacks can be run more than once (they don't get deleted or marked when
83// run). However, this precludes using base::Passed (see below).
84//
85// void DoSomething(const base::Callback<double(double)>& callback) {
86// double myresult = callback.Run(3.14159);
87// myresult += callback.Run(2.71828);
88// }
89//
90// PASSING UNBOUND INPUT PARAMETERS
91//
92// Unbound parameters are specified at the time a callback is Run(). They are
93// specified in the Callback template type:
94//
95// void MyFunc(int i, const std::string& str) {}
96// base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
97// cb.Run(23, "hello, world");
98//
99// PASSING BOUND INPUT PARAMETERS
100//
101// Bound parameters are specified when you create thee callback as arguments
102// to Bind(). They will be passed to the function and the Run()ner of the
103// callback doesn't see those values or even know that the function it's
104// calling.
105//
106// void MyFunc(int i, const std::string& str) {}
107// base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");
108// cb.Run();
109//
110// A callback with no unbound input parameters (base::Callback<void(void)>)
111// is called a base::Closure. So we could have also written:
112//
113// base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
114//
115// When calling member functions, bound parameters just go after the object
116// pointer.
117//
118// base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
119//
120// PARTIAL BINDING OF PARAMETERS
121//
122// You can specify some parameters when you create the callback, and specify
123// the rest when you execute the callback.
124//
125// void MyFunc(int i, const std::string& str) {}
[email protected]3c69b0d2012-08-13 23:11:50126// base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
[email protected]24292642012-07-12 20:06:40127// cb.Run("hello world");
128//
129// When calling a function bound parameters are first, followed by unbound
130// parameters.
131//
132//
133// -----------------------------------------------------------------------------
134// Quick reference for advanced binding
135// -----------------------------------------------------------------------------
136//
137// BINDING A CLASS METHOD WITH WEAK POINTERS
138//
139// base::Bind(&MyClass::Foo, GetWeakPtr());
140//
[email protected]006c48c2014-06-26 06:07:45141// The callback will not be run if the object has already been destroyed.
142// DANGER: weak pointers are not threadsafe, so don't use this
[email protected]24292642012-07-12 20:06:40143// when passing between threads!
144//
145// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
146//
147// base::Bind(&MyClass::Foo, base::Unretained(this));
148//
149// This disables all lifetime management on the object. You're responsible
150// for making sure the object is alive at the time of the call. You break it,
151// you own it!
152//
153// BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
154//
155// MyClass* myclass = new MyClass;
156// base::Bind(&MyClass::Foo, base::Owned(myclass));
157//
158// The object will be deleted when the callback is destroyed, even if it's
159// not run (like if you post a task during shutdown). Potentially useful for
160// "fire and forget" cases.
161//
162// IGNORING RETURN VALUES
163//
164// Sometimes you want to call a function that returns a value in a callback
165// that doesn't expect a return value.
166//
167// int DoSomething(int arg) { cout << arg << endl; }
168// base::Callback<void<int>) cb =
169// base::Bind(base::IgnoreResult(&DoSomething));
170//
171//
172// -----------------------------------------------------------------------------
173// Quick reference for binding parameters to Bind()
174// -----------------------------------------------------------------------------
175//
176// Bound parameters are specified as arguments to Bind() and are passed to the
177// function. A callback with no parameters or no unbound parameters is called a
178// Closure (base::Callback<void(void)> and base::Closure are the same thing).
179//
180// PASSING PARAMETERS OWNED BY THE CALLBACK
181//
182// void Foo(int* arg) { cout << *arg << endl; }
183// int* pn = new int(1);
184// base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
185//
186// The parameter will be deleted when the callback is destroyed, even if it's
187// not run (like if you post a task during shutdown).
188//
189// PASSING PARAMETERS AS A scoped_ptr
190//
191// void TakesOwnership(scoped_ptr<Foo> arg) {}
192// scoped_ptr<Foo> f(new Foo);
193// // f becomes null during the following call.
194// base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));
195//
196// Ownership of the parameter will be with the callback until the it is run,
197// when ownership is passed to the callback function. This means the callback
198// can only be run once. If the callback is never run, it will delete the
199// object when it's destroyed.
200//
201// PASSING PARAMETERS AS A scoped_refptr
202//
203// void TakesOneRef(scoped_refptr<Foo> arg) {}
204// scoped_refptr<Foo> f(new Foo)
205// base::Closure cb = base::Bind(&TakesOneRef, f);
206//
207// This should "just work." The closure will take a reference as long as it
208// is alive, and another reference will be taken for the called function.
209//
210// PASSING PARAMETERS BY REFERENCE
211//
[email protected]d3eecdd2013-11-28 05:18:53212// Const references are *copied* unless ConstRef is used. Example:
213//
214// void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
[email protected]24292642012-07-12 20:06:40215// int n = 1;
[email protected]d3eecdd2013-11-28 05:18:53216// base::Closure has_copy = base::Bind(&foo, n);
[email protected]24292642012-07-12 20:06:40217// base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
218// n = 2;
[email protected]d3eecdd2013-11-28 05:18:53219// foo(n); // Prints "2 0xaaaaaaaaaaaa"
220// has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
221// has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
[email protected]24292642012-07-12 20:06:40222//
223// Normally parameters are copied in the closure. DANGER: ConstRef stores a
224// const reference instead, referencing the original parameter. This means
225// that you must ensure the object outlives the callback!
226//
227//
228// -----------------------------------------------------------------------------
229// Implementation notes
230// -----------------------------------------------------------------------------
[email protected]b38d3572011-02-15 01:27:38231//
232// WHERE IS THIS DESIGN FROM:
233//
234// The design Callback and Bind is heavily influenced by C++'s
235// tr1::function/tr1::bind, and by the "Google Callback" system used inside
236// Google.
237//
238//
239// HOW THE IMPLEMENTATION WORKS:
240//
241// There are three main components to the system:
242// 1) The Callback classes.
243// 2) The Bind() functions.
[email protected]7f4ad942011-12-13 00:06:28244// 3) The arguments wrappers (e.g., Unretained() and ConstRef()).
[email protected]b38d3572011-02-15 01:27:38245//
246// The Callback classes represent a generic function pointer. Internally,
247// it stores a refcounted piece of state that represents the target function
248// and all its bound parameters. Each Callback specialization has a templated
[email protected]e24f8762011-12-20 00:10:04249// constructor that takes an BindState<>*. In the context of the constructor,
250// the static type of this BindState<> pointer uniquely identifies the
251// function it is representing, all its bound parameters, and a Run() method
252// that is capable of invoking the target.
[email protected]b38d3572011-02-15 01:27:38253//
[email protected]e24f8762011-12-20 00:10:04254// Callback's constructor takes the BindState<>* that has the full static type
255// and erases the target function type as well as the types of the bound
256// parameters. It does this by storing a pointer to the specific Run()
257// function, and upcasting the state of BindState<>* to a
258// BindStateBase*. This is safe as long as this BindStateBase pointer
259// is only used with the stored Run() pointer.
[email protected]b38d3572011-02-15 01:27:38260//
[email protected]e24f8762011-12-20 00:10:04261// To BindState<> objects are created inside the Bind() functions.
262// These functions, along with a set of internal templates, are responsible for
[email protected]b38d3572011-02-15 01:27:38263//
264// - Unwrapping the function signature into return type, and parameters
265// - Determining the number of parameters that are bound
[email protected]e24f8762011-12-20 00:10:04266// - Creating the BindState storing the bound parameters
[email protected]b38d3572011-02-15 01:27:38267// - Performing compile-time asserts to avoid error-prone behavior
[email protected]e24f8762011-12-20 00:10:04268// - Returning an Callback<> with an arity matching the number of unbound
269// parameters and that knows the correct refcounting semantics for the
270// target object if we are binding a method.
[email protected]b38d3572011-02-15 01:27:38271//
272// The Bind functions do the above using type-inference, and template
273// specializations.
274//
275// By default Bind() will store copies of all bound parameters, and attempt
276// to refcount a target object if the function being bound is a class method.
[email protected]83aa04a32012-10-11 03:54:33277// These copies are created even if the function takes parameters as const
[email protected]68639bbe2012-12-06 19:00:50278// references. (Binding to non-const references is forbidden, see bind.h.)
[email protected]b38d3572011-02-15 01:27:38279//
280// To change this behavior, we introduce a set of argument wrappers
[email protected]7f4ad942011-12-13 00:06:28281// (e.g., Unretained(), and ConstRef()). These are simple container templates
[email protected]b38d3572011-02-15 01:27:38282// that are passed by value, and wrap a pointer to argument. See the
283// file-level comment in base/bind_helpers.h for more info.
284//
285// These types are passed to the Unwrap() functions, and the MaybeRefcount()
286// functions respectively to modify the behavior of Bind(). The Unwrap()
287// and MaybeRefcount() functions change behavior by doing partial
288// specialization based on whether or not a parameter is a wrapper type.
289//
290// ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.
291//
292//
293// WHY NOT TR1 FUNCTION/BIND?
294//
295// Direct use of tr1::function and tr1::bind was considered, but ultimately
296// rejected because of the number of copy constructors invocations involved
297// in the binding of arguments during construction, and the forwarding of
298// arguments during invocation. These copies will no longer be an issue in
299// C++0x because C++0x will support rvalue reference allowing for the compiler
300// to avoid these copies. However, waiting for C++0x is not an option.
301//
302// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
303// tr1::bind call itself will invoke a non-trivial copy constructor three times
304// for each bound parameter. Also, each when passing a tr1::function, each
305// bound argument will be copied again.
306//
307// In addition to the copies taken at binding and invocation, copying a
308// tr1::function causes a copy to be made of all the bound parameters and
309// state.
310//
311// Furthermore, in Chromium, it is desirable for the Callback to take a
312// reference on a target object when representing a class method call. This
313// is not supported by tr1.
314//
315// Lastly, tr1::function and tr1::bind has a more general and flexible API.
316// This includes things like argument reordering by use of
317// tr1::bind::placeholder, support for non-const reference parameters, and some
[email protected]7f4ad942011-12-13 00:06:28318// limited amount of subtyping of the tr1::function object (e.g.,
[email protected]b38d3572011-02-15 01:27:38319// tr1::function<int(int)> is convertible to tr1::function<void(int)>).
320//
321// These are not features that are required in Chromium. Some of them, such as
322// allowing for reference parameters, and subtyping of functions, may actually
[email protected]9f6c5292011-04-19 18:22:00323// become a source of errors. Removing support for these features actually
[email protected]b38d3572011-02-15 01:27:38324// allows for a simpler implementation, and a terser Currying API.
325//
326//
327// WHY NOT GOOGLE CALLBACKS?
328//
329// The Google callback system also does not support refcounting. Furthermore,
330// its implementation has a number of strange edge cases with respect to type
331// conversion of its arguments. In particular, the argument's constness must
332// at times match exactly the function signature, or the type-inference might
333// break. Given the above, writing a custom solution was easier.
334//
335//
336// MISSING FUNCTIONALITY
337// - Invoking the return of Bind. Bind(&foo).Run() does not work;
338// - Binding arrays to functions that take a non-const pointer.
339// Example:
340// void Foo(const char* ptr);
341// void Bar(char* ptr);
342// Bind(&Foo, "test");
343// Bind(&Bar, "test"); // This fails because ptr is not const.
[email protected]2041cf342010-02-19 03:15:59344
[email protected]b38d3572011-02-15 01:27:38345namespace base {
346
347// First, we forward declare the Callback class template. This informs the
348// compiler that the template only has 1 type parameter which is the function
349// signature that the Callback is representing.
350//
[email protected]fccef1552011-11-28 22:13:54351// After this, create template specializations for 0-7 parameters. Note that
[email protected]b38d3572011-02-15 01:27:38352// even though the template typelist grows, the specialization still
353// only has one type: the function signature.
[email protected]d7f75242011-12-07 21:44:06354//
355// If you are thinking of forward declaring Callback in your own header file,
356// please include "base/callback_forward.h" instead.
[email protected]b38d3572011-02-15 01:27:38357template <typename Sig>
358class Callback;
[email protected]4346ef912011-02-19 00:52:15359
[email protected]e24f8762011-12-20 00:10:04360namespace internal {
361template <typename Runnable, typename RunType, typename BoundArgsType>
362struct BindState;
363} // namespace internal
364
tzikc87149e2014-11-20 01:08:20365template <typename R, typename... Args>
366class Callback<R(Args...)> : public internal::CallbackBase {
[email protected]2041cf342010-02-19 03:15:59367 public:
tzikc87149e2014-11-20 01:08:20368 typedef R(RunType)(Args...);
[email protected]b38d3572011-02-15 01:27:38369
[email protected]e24f8762011-12-20 00:10:04370 Callback() : CallbackBase(NULL) { }
[email protected]b38d3572011-02-15 01:27:38371
[email protected]b38d3572011-02-15 01:27:38372 // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
373 // return the exact Callback<> type. See base/bind.h for details.
[email protected]3c69b0d2012-08-13 23:11:50374 template <typename Runnable, typename BindRunType, typename BoundArgsType>
375 Callback(internal::BindState<Runnable, BindRunType,
376 BoundArgsType>* bind_state)
[email protected]e24f8762011-12-20 00:10:04377 : CallbackBase(bind_state) {
[email protected]e24f8762011-12-20 00:10:04378 // Force the assignment to a local variable of PolymorphicInvoke
[email protected]7296f2762011-11-21 19:23:44379 // so the compiler will typecheck that the passed in Run() method has
380 // the correct type.
[email protected]e24f8762011-12-20 00:10:04381 PolymorphicInvoke invoke_func =
[email protected]3c69b0d2012-08-13 23:11:50382 &internal::BindState<Runnable, BindRunType, BoundArgsType>
[email protected]e24f8762011-12-20 00:10:04383 ::InvokerType::Run;
[email protected]7296f2762011-11-21 19:23:44384 polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
[email protected]2041cf342010-02-19 03:15:59385 }
386
[email protected]481915a772011-09-10 03:14:35387 bool Equals(const Callback& other) const {
388 return CallbackBase::Equals(other);
389 }
390
tzikc87149e2014-11-20 01:08:20391 R Run(typename internal::CallbackParamTraits<Args>::ForwardType... args)
392 const {
[email protected]15fcb6592011-02-18 04:05:14393 PolymorphicInvoke f =
394 reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
[email protected]2041cf342010-02-19 03:15:59395
tzikc87149e2014-11-20 01:08:20396 return f(bind_state_.get(), internal::CallbackForward(args)...);
[email protected]15fcb6592011-02-18 04:05:14397 }
[email protected]7296f2762011-11-21 19:23:44398
399 private:
400 typedef R(*PolymorphicInvoke)(
401 internal::BindStateBase*,
tzikc87149e2014-11-20 01:08:20402 typename internal::CallbackParamTraits<Args>::ForwardType...);
[email protected]2041cf342010-02-19 03:15:59403};
404
[email protected]c81c9f32014-07-03 06:10:13405// Syntactic sugar to make Callback<void(void)> easier to declare since it
[email protected]b38d3572011-02-15 01:27:38406// will be used in a lot of APIs with delayed execution.
407typedef Callback<void(void)> Closure;
408
409} // namespace base
[email protected]2041cf342010-02-19 03:15:59410
tzikc87149e2014-11-20 01:08:20411#endif // BASE_CALLBACK_H_