Home | History | Annotate | Download | only in base
      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
      3 $$ can be found here:
      4 $$
      5 $$ http://code.google.com/p/googletest/wiki/PumpManual
      6 $$
      7 
      8 $$ See comment for MAX_ARITY in base/bind.h.pump.
      9 $var MAX_ARITY = 7
     10 
     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.
     14 
     15 #ifndef BASE_CALLBACK_H_
     16 #define BASE_CALLBACK_H_
     17 
     18 #include "base/callback_forward.h"
     19 #include "base/callback_internal.h"
     20 #include "base/template_util.h"
     21 
     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.
     24 
     25 // -----------------------------------------------------------------------------
     26 // Introduction
     27 // -----------------------------------------------------------------------------
     28 //
     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.
     32 //
     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.
     38 //
     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.
     43 //
     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 //
     54 // -----------------------------------------------------------------------------
     55 // Quick reference for basic stuff
     56 // -----------------------------------------------------------------------------
     57 //
     58 // BINDING A BARE FUNCTION
     59 //
     60 //   int Return5() { return 5; }
     61 //   base::Callback<int(void)> func_cb = base::Bind(&Return5);
     62 //   LOG(INFO) << func_cb.Run();  // Prints 5.
     63 //
     64 // BINDING A CLASS METHOD
     65 //
     66 //   The first argument to bind is the member function to call, the second is
     67 //   the object on which to call it.
     68 //
     69 //   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.
     77 //
     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.
     82 //
     83 // RUNNING A CALLBACK
     84 //
     85 //   Callbacks can be run with their "Run" method, which has the same
     86 //   signature as the template argument to the callback.
     87 //
     88 //   void DoSomething(const base::Callback<void(int, std::string)>& callback) {
     89 //     callback.Run(5, "hello");
     90 //   }
     91 //
     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).
     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) {}
    136 //   base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
    137 //   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 //
    151 //   The callback will not be issued if the object is destroyed at the time
    152 //   it's issued. DANGER: weak pointers are not threadsafe, so don't use this
    153 //   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 // -----------------------------------------------------------------------------
    236 //
    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.
    249 //   3) The arguments wrappers (e.g., Unretained() and ConstRef()).
    250 //
    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.
    258 //
    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.
    265 //
    266 // To BindState<> objects are created inside the Bind() functions.
    267 // These functions, along with a set of internal templates, are responsible for
    268 //
    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.
    276 //
    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.
    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.)
    284 //
    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.
    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
    323 // limited amount of subtyping of the tr1::function object (e.g.,
    324 // 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
    328 // become a source of errors. Removing support for these features actually
    329 // 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 
    350 namespace 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.
    359 //
    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>
    363 class Callback;
    364 
    365 namespace internal {
    366 template <typename Runnable, typename RunType, typename BoundArgsType>
    367 struct BindState;
    368 }  // namespace internal
    369 
    370 
    371 $range ARITY 0..MAX_ARITY
    372 $for ARITY [[
    373 $range ARG 1..ARITY
    374 
    375 $if ARITY == 0 [[
    376 template <typename R>
    377 class Callback<R(void)> : public internal::CallbackBase {
    378 ]] $else [[
    379 template <typename R, $for ARG , [[typename A$(ARG)]]>
    380 class Callback<R($for ARG , [[A$(ARG)]])> : public internal::CallbackBase {
    381 ]]
    382 
    383  public:
    384   typedef R(RunType)($for ARG , [[A$(ARG)]]);
    385 
    386   Callback() : CallbackBase(NULL) { }
    387 
    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) {
    394 
    395     // Force the assignment to a local variable of PolymorphicInvoke
    396     // so the compiler will typecheck that the passed in Run() method has
    397     // the correct type.
    398     PolymorphicInvoke invoke_func =
    399         &internal::BindState<Runnable, BindRunType, BoundArgsType>
    400             ::InvokerType::Run;
    401     polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
    402   }
    403 
    404   bool Equals(const Callback& other) const {
    405     return CallbackBase::Equals(other);
    406   }
    407 
    408   R Run($for ARG ,
    409         [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType a$(ARG)]]) const {
    410     PolymorphicInvoke f =
    411         reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
    412 
    413     return f(bind_state_.get()[[]]
    414 $if ARITY != 0 [[, ]]
    415 $for ARG ,
    416              [[internal::CallbackForward(a$(ARG))]]);
    417   }
    418 
    419  private:
    420   typedef R(*PolymorphicInvoke)(
    421       internal::BindStateBase*[[]]
    422 $if ARITY != 0 [[, ]]
    423 $for ARG , [[typename internal::CallbackParamTraits<A$(ARG)>::ForwardType]]);
    424 
    425 };
    426 
    427 
    428 ]]  $$ for ARITY
    429 
    430 // Syntactic sugar to make Callbacks<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;
    433 
    434 }  // namespace base
    435 
    436 #endif  // BASE_CALLBACK_H
    437