diff --git a/faq.html b/doc/faq.html similarity index 91% rename from faq.html rename to doc/faq.html index d922646..d7dcefa 100644 --- a/faq.html +++ b/doc/faq.html @@ -5,7 +5,7 @@ -

boost::function Frequently Asked Questions

+

boost::function Frequently Asked Questions

Q: I see void pointers; is this [mess] type safe?

Yes, boost::function is type safe even though it uses void pointers and pointers to functions returning void and taking no arguments. Essentially, all type information is encoded in the functions that manage and invoke function pointers and function objects. Only these functions are instantiated with the exact type that is pointed to by the void pointer or pointer to void function. The reason that both are required is that one may cast between void pointers and object pointers safely or between different types of function pointers (provided you don't invoke a function pointer with the wrong type). @@ -35,13 +35,13 @@ void g() { return f(); }

In November and December of 2000, the issue of cloning vs. reference counting was debated at length and it was decided that cloning gave more predictable semantics. I won't rehash the discussion here, but if it cloning is incorrect for a particular application a reference-counting allocator could be used.

Q: How do I assign from a member function?

-

Member function assignments are not included directly in boost::function because they do not conform to the syntax of function objects. Several libraries exist to wrap member functions in a function object and/or bind the first argument to the member function (the this pointer). A few libraries are described in the Boost.Function documentation. +

Member function assignments are not included directly in boost::function because they do not conform to the syntax of function objects. Several libraries exist to wrap member functions in a function object and/or bind the first argument to the member function (the this pointer). A few libraries are described in the Boost.Function documentation.


Doug Gregor
-Last modified: Sun Jun 17 10:06:31 EDT 2001 +Last modified: Sat Jul 14 16:00:11 EDT 2001 \ No newline at end of file diff --git a/doc/reference.html b/doc/reference.html new file mode 100644 index 0000000..b6ecf62 --- /dev/null +++ b/doc/reference.html @@ -0,0 +1,255 @@ + + + + Boost.Function Reference Manual + + + + +

Boost.Function Reference Manual

+ +

Header <boost/function.hpp> synopsis

+

Here MAX_ARGS is an implementation-defined constant that defines the maximum number of function arguments supported by Boost.Function and will be at least 10. The MAX_ARGS constant referred to in this document need not have any direct representation in the library. + +

+namespace boost {
+  class function_base
+  {
+    bool empty() const;
+    operator bool() const;
+  };
+
+  // For N in [0, MAX_ARGS]
+  template<typename ResultType,
+           typename Arg1,
+	   typename Arg2,
+           ...
+           typename ArgN,
+	   typename Policy    = empty_function_policy,
+	   typename Mixin     = empty_function_mixin,
+	   typename Allocator = std::allocator<function_base> >
+  class functionN : public function_base, public Mixin
+  {
+    typedef ResultType result_type;
+    typedef Policy     policy_type;
+    typedef Mixin      mixin_type;
+    typedef Allocator  allocator_type;
+
+    typedef Arg1 argument_type;        // If N == 1
+
+    typedef Arg1 first_argument_type;  // If N == 2
+    typedef Arg2 second_argument_type; // If N == 2
+
+    // Construction
+    explicit functionN(const Mixin& = Mixin());
+    functionN(const functionN&);
+    template<typename F> functionN(const F&, const Mixin& = Mixin());
+    
+    // Assignment
+    functionN& operator=(const functionN&);
+    template<typename F> functionN& operator=(const F&);
+    void set(const functionN&);
+    template<typename F> void set(const F&);
+    void swap(functionN&);
+    void clear();
+
+    // Invocation
+    result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN);
+    result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN) const;
+  };
+
+  template<typename ResultType,
+           typename Arg1,
+	   typename Arg2,
+           ...
+	   typename ArgN,
+           typename Policy,
+           typename Mixin,
+           typename Allocator>
+  inline void swap(const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>&,
+                   const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>&);
+
+  // For any N in [0, MAX_ARGS]
+  template<typename ResultType,
+           typename Arg1,
+	   typename Arg2,
+           ...
+           typename ArgN,
+           typename ArgN+1 = implementation-defined,
+           typename ArgN+2 = implementation-defined,
+	   ...
+	   typename ArgMAX_ARGS = implementation-defined>
+  class function : public functionN<Arg1, Arg2, ..., ArgN>
+  {
+    // Construction
+    function();
+    function(const function&);
+    functionN(const functionN&);
+    template<typename F> functionN(const F&);
+    
+    // Assignment
+    function& operator=(const function&);
+    functionN& operator=(const functionN&);
+    template<typename F> function& operator=(const F&);
+    void set(const function&);
+    void set(const functionN&);
+    template<typename F> void set(const F&);
+  };
+
+  template<typename ResultType,
+           typename Arg1,
+	   typename Arg2,
+           ...
+	   typename ArgMAX_ARGS>
+  inline void swap(const function<Arg1, Arg2, ...ArgMAX_ARGS>&,
+                   const function<Arg1, Arg2, ...ArgMAX_ARGS>&);
+}	   
+
+ +

Class function_base

+

Class function_base is the common base class for all Boost.Function objects. Objects of type function_base may not be created directly. + +

bool empty() const +

+ +

operator bool() const +

+ +

Class template functionN

+

Class template functionN is actually a family of related classes function0, function1, etc., up to some implementation-defined maximum. In this context, N refers to the number of parameters and f refers to the implicit object parameter. + +

explicit functionN(const Mixin& = Mixin()); +

+ +

functionN(const functionN& g); +

+ +

template<typename F> functionN(const F& g, const Mixin& = Mixin()); +

+ +

functionN& operator=(const functionN& g); +

+ +

template<typename F> functionN& operator=(const F& g); +

+ +

void set(const functionN& g); +

+ +

template<typename F> void set(const F& g); +

+ +

void swap(functionN& g); +

+ +

void clear(); +

+ +

result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN); +

+ +

result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN) const; +

+ +

Class template function

+

Class template function is a thin wrapper around the numbered class templates function0, function1, etc. It accepts up to MAX_ARGS arguments, but when passed N arguments it will derive from functionN specialized with the arguments it receives. + +

The semantics of all operations in class template function are equivalent to that of the underlying functionN object, although additional member functions are required to allow proper copy construction and copy assignment of function objects. + +

Operations

+

+

+template<typename ResultType,
+         typename Arg1,
+	 typename Arg2,
+         ...
+	 typename ArgN,
+         typename Policy,
+         typename Mixin,
+         typename Allocator>
+inline void swap(const functionN<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>& f,
+                 const functionN<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>& g);
+
+ + +

+

+template<typename ResultType,
+         typename Arg1,
+	 typename Arg2,
+         ...
+	 typename ArgMAX_ARGS>
+inline void swap(const function<Arg1, Arg2, ...ArgMAX_ARGS>& f,
+                 const function<Arg1, Arg2, ...ArgMAX_ARGS>& g);
+
+ + +
+
Douglas Gregor
+ + +Last modified: Sat Jul 14 15:55:35 EDT 2001 + + + diff --git a/doc/tutorial.html b/doc/tutorial.html new file mode 100644 index 0000000..891b728 --- /dev/null +++ b/doc/tutorial.html @@ -0,0 +1,167 @@ + + + + Boost.Function Tutorial + + + + +

Boost.Function Tutorial

+ +

Basic usage

+

A function wrapper is defined simply by instantiating the function class template with the desired return type and argument types. Any number of arguments may be supplied, up to some implementation-defined limit (10 is the default maximum). The following declares a function object wrapper f that takes two int parameters and returns a float: +

+boost::function<float, int, int> f;
+
+ +

By default, function object wrappers are empty, so we can create a +function object to assign to f: +

+struct int_div { 
+  float operator()(int x, int y) const { return ((float)x)/y; }; 
+};
+
+f = int_div();
+
+ +

Now we can use f to execute the underlying function object +int_div: +

+std::cout << f(5, 3) << std::endl;
+
+ +

We are free to assign any compatible function object to f. If int_div had been declared to take two long operands, +the implicit conversions would have been applied to the arguments without any user interference. The only limit on the types of arguments is that they be CopyConstructible, so we can even use references and arrays: +

+boost::function<void, int[], int, int&, float&> sum_avg;
+
+void do_sum_avg(int values[], int n, int& sum, float& avg)
+{
+  sum = 0;
+  for (int i = 0; i < n; i++)
+    sum += values[i];
+  avg = (float)sum / n;
+}
+
+sum_avg = &do_sum_avg;
+
+ +

Invoking a function object wrapper that does not actually contain a function object is a precondition violation, much like trying to call through a null function pointer. We can check for an empty function object wrapper by querying its empty() method or, more succinctly, by using it in a boolean context: if it evaluates true, it contains a function object target, i.e., +

+if (f)
+  std::cout << f(5, 3) << std::endl;
+else
+  std::cout << "f has no target, so it is unsafe to call" << std::endl;
+
+ +

We can clear out a function target using the clear() member function. + +

Free functions

+

Free function pointers can be considered singleton function objects with const function call operators, and can therefore be directly used with the function object wrappers: +

+  float mul_ints(int x, int y) { return ((float)x) * y; }
+  f = &mul_ints;
+
+ +

Member functions

+ +

In many systems, callbacks often call to member functions of a particular +object. Handling argument binding is beyond the scope of Boost.Function. However, there are several libraries that perform 'argument binding', including +

+ +

The function family

+

The header <boost/function.hpp> defines the primary entry point to the function object wrappers, the class template boost::function. This class template is essentially a thin wrapper around a set of similar numbered function object wrappers, boost::function0, boost::function1, etc., where the number indicates the number of arguments passed to the function object target. The declaration of f above could also be written as: +

+boost::function2<float, int, int> f;
+
+ +

The numbered class templates contain most of the implementation and are each distinct class templates. They may be helpful if used in shared libraries, where the number of arguments supported by Boost.Function may change between revisions. Additionally, some compilers (e.g., Microsoft Visual C++ 6.0) have been known to be incapable of compiling boost::function in some instances but are able to handle the numbered variants. + +

Advanced usage

+

The boost::function family supports additional customization by means of policies, mixins, and allocators. The specific usage of each of these will be explained in later sections, but they share a common problem: how to replace each default with your own version. + +

With boost::function it is not so clear, because support for an arbitrary number of parameters means that it is impossible to specify just the last parameter, but not 5 of the parameters in between. Therefore, boost::function doubles as a generative interface for the underlying numbered class templates that uses named template parameters. For instance, to specify both a policy and an allocator for a function object wrapper f taking an int and returning an int, use: +

+  function<int, int>::policy<MyPolicy>::allocator<MyAllocator>::type f;
+
+ +

The named template parameters policy, mixin and allocator each take one template parameter (the replacement class) and may be nested as above to generate a function object wrapper. The ::type at the end accesses the actual type that fits the given properties. + +

Policies

+

Policies define what happens directly before and directly after an invocation of a function object target is made. A policy must have two member functions, precall and postcall, each of which must be able to accept a const function object wrapper pointer. The following policy will print "before" prior to execution and "after" afterwards: + +

+struct print_policy {
+  void precall(const boost::function_base*) { std::cout << "before"; }
+  void postcall(const boost::function_base*) { std::cout << "after"; }
+};
+
+ +

A new instance of the policy class will be created prior to calling the function object target and will be preserved until after the call has returned. Therefore, for any invocation the precall and postcall will be executed on the same policy class instance; however, policy class instances will not be kept between target invocations. + +

Policies are further described in the Boost discussion on generic programming techniques. + +

Mixins

+

The function object wrappers allow any class to be "mixed in" as a base class. This allows extra members and/or functionality to be included by the user. This can be used, for instance, to overcome the limitations of policies by storing data between invocations in a base class instead of in a static member of a policy class. + +

Allocators

+

The function object wrappers allow the user to specify a new allocator to handle the cloning of function object targets (when the wrappers are copied). The allocators used are the same as the C++ standard library allocators. The wrappers assume the allocators are stateless, and will create a new instance each time they are used (because they are rebound very often). This shares the semantics of most standard library implementations, and is explicitly allowed by the C++ standard. + +

Example: Synchronized callbacks

+

Synchronization of callbacks in a multithreaded environment is extremely important. Using mixins and policies, a Boost.Function object may implement its own synchronization policy that ensures that only one thread can be in the callback function at any given point in time. + +

We will use the prototype Boost.Threads library for its recursive_mutex. Since the mutex is on a per-callback basis, we will add a mutex to the boost::function by mixin it in with this mixin class: +

+class SynchronizedMixin {
+  mutable boost::recursive_mutex mutex;
+};
+
+ +

Next, we create a policy that obtains a lock before the target is called (via the precall function) and releases the lock after the target has been called (via the postcall function): + +

+class SynchronizedPolicy {
+  std::auto_ptr<boost::recursive_mutex::lock> lock;
+
+  void precall(const SynchronizedMixin* f) 
+  {
+    lock.reset(new boost::recursive_mutex::lock(f->mutex));
+  }
+
+  void postcall(const SynchronizedMixin* f)
+  {
+    lock.reset();
+  }
+};
+
+ +

The use of std::auto_ptr ensures that the lock will be destroyed (and therefore released) if an exception is thrown by the target function. Now we can use the policy and mixin together to create a synchronized callback: + +

+boost::function2<float, int, int, SynchronizedPolicy, SynchronizedMixin> f;
+
+ +
+
Douglas Gregor
+ + +Last modified: Fri Jul 13 23:58:17 EDT 2001 + + + diff --git a/example/bind1st.cpp b/example/bind1st.cpp new file mode 100644 index 0000000..875481a --- /dev/null +++ b/example/bind1st.cpp @@ -0,0 +1,38 @@ +// Boost.Function library examples + +// Copyright (C) 2001 Doug Gregor (gregod@cs.rpi.edu) +// +// Permission to copy, use, sell and distribute this software is granted +// provided this copyright notice appears in all copies. +// Permission to modify the code and to distribute modified code is granted +// provided this copyright notice appears in all copies, and a notice +// that the code was modified is included with the copyright notice. +// +// This software is provided "as is" without express or implied warranty, +// and with no claim as to its suitability for any purpose. + +// For more information, see http://www.boost.org + +#include +#include +#include + +struct X { + X(int val) : value(val) {} + + int foo(int x) { return x * value; } + + int value; +}; + + +int +main() +{ + boost::function f; + X x(7); + f = std::bind1st(std::mem_fun(&X::foo), &x); + + std::cout << f(5) << std::endl; // Call x.foo(5) + return 0; +} diff --git a/example/int_div.cpp b/example/int_div.cpp new file mode 100644 index 0000000..b98cc36 --- /dev/null +++ b/example/int_div.cpp @@ -0,0 +1,32 @@ +// Boost.Function library examples + +// Copyright (C) 2001 Doug Gregor (gregod@cs.rpi.edu) +// +// Permission to copy, use, sell and distribute this software is granted +// provided this copyright notice appears in all copies. +// Permission to modify the code and to distribute modified code is granted +// provided this copyright notice appears in all copies, and a notice +// that the code was modified is included with the copyright notice. +// +// This software is provided "as is" without express or implied warranty, +// and with no claim as to its suitability for any purpose. + +// For more information, see http://www.boost.org + +#include +#include + +struct int_div { + float operator()(int x, int y) const { return ((float)x)/y; }; +}; + +int +main() +{ + boost::function f; + f = int_div(); + + std::cout << f(5, 3) << std::endl; // 1.66667 + + return 0; +} diff --git a/example/sum_avg.cpp b/example/sum_avg.cpp new file mode 100644 index 0000000..204ac8f --- /dev/null +++ b/example/sum_avg.cpp @@ -0,0 +1,42 @@ +// Boost.Function library examples + +// Copyright (C) 2001 Doug Gregor (gregod@cs.rpi.edu) +// +// Permission to copy, use, sell and distribute this software is granted +// provided this copyright notice appears in all copies. +// Permission to modify the code and to distribute modified code is granted +// provided this copyright notice appears in all copies, and a notice +// that the code was modified is included with the copyright notice. +// +// This software is provided "as is" without express or implied warranty, +// and with no claim as to its suitability for any purpose. + +// For more information, see http://www.boost.org + +#include +#include + +void do_sum_avg(int values[], int n, int& sum, float& avg) +{ + sum = 0; + for (int i = 0; i < n; i++) + sum += values[i]; + avg = (float)sum / n; +} + +int +main() +{ + boost::function sum_avg; + + sum_avg = &do_sum_avg; + + int values[5] = { 1, 1, 2, 3, 5 }; + int sum; + float avg; + sum_avg(values, 5, sum, avg); + + std::cout << "sum = " << sum << std::endl; + std::cout << "avg = " << avg << std::endl; + return 0; +} diff --git a/index.html b/index.html index 676845b..bbfaf63 100644 --- a/index.html +++ b/index.html @@ -13,414 +13,16 @@

Generally, any place in which a function pointer would be used to defer a call or make a callback, Boost.Function can be used instead to allow the user greater flexibility in the implementation of the target. Targets can be any 'compatible' function object (or function pointer), meaning that the arguments to the interface designated by Boost.Function can be converted to the arguments of the target function object.

- -

Header <boost/function.hpp> synopsis

-

Here MAX_ARGS is an implementation-defined constant that defines the maximum number of function arguments supported by Boost.Function and will be at least 10. The MAX_ARGS constant referred to in this document need not have any direct representation in the library. - -

-namespace boost {
-  class function_base
-  {
-    bool empty() const;
-    operator bool() const;
-  };
-
-  // For N in [0, MAX_ARGS]
-  template<typename ResultType,
-           typename Arg1,
-	   typename Arg2,
-           ...
-           typename ArgN,
-	   typename Policy    = empty_function_policy,
-	   typename Mixin     = empty_function_mixin,
-	   typename Allocator = std::allocator<function_base> >
-  class functionN : public function_base, public Mixin
-  {
-    typedef ResultType result_type;
-    typedef Policy     policy_type;
-    typedef Mixin      mixin_type;
-    typedef Allocator  allocator_type;
-
-    typedef Arg1 argument_type;        // If N == 1
-
-    typedef Arg1 first_argument_type;  // If N == 2
-    typedef Arg2 second_argument_type; // If N == 2
-
-    // Construction
-    functionN();
-    functionN(const functionN&);
-    template<typename F> functionN(const F&);
-    
-    // Assignment
-    functionN& operator=(const functionN&);
-    template<typename F> functionN& operator=(const F&);
-    void set(const functionN&);
-    template<typename F> void set(const F&);
-    void swap(functionN&);
-    void clear();
-
-    // Invocation
-    result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN);
-    result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN) const;
-  };
-
-  template<typename ResultType,
-           typename Arg1,
-	   typename Arg2,
-           ...
-	   typename ArgN,
-           typename Policy,
-           typename Mixin,
-           typename Allocator>
-  inline void swap(const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>&,
-                   const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>&);
-
-  // For any N in [0, MAX_ARGS]
-  template<typename ResultType,
-           typename Arg1,
-	   typename Arg2,
-           ...
-           typename ArgN,
-           typename ArgN+1 = implementation-defined,
-           typename ArgN+2 = implementation-defined,
-	   ...
-	   typename ArgMAX_ARGS = implementation-defined>
-  class function : public functionN<Arg1, Arg2, ..., ArgN>
-  {
-    // Construction
-    function();
-    function(const function&);
-    functionN(const functionN&);
-    template<typename F> functionN(const F&);
-    
-    // Assignment
-    function& operator=(const function&);
-    functionN& operator=(const functionN&);
-    template<typename F> function& operator=(const F&);
-    void set(const function&);
-    void set(const functionN&);
-    template<typename F> void set(const F&);
-  };
-
-  template<typename ResultType,
-           typename Arg1,
-	   typename Arg2,
-           ...
-	   typename ArgMAX_ARGS>
-  inline void swap(const function<Arg1, Arg2, ...ArgMAX_ARGS>&,
-                   const function<Arg1, Arg2, ...ArgMAX_ARGS>&);
-}	   
-
- -

Class function_base

-

Class function_base is the common base class for all Boost.Function objects. Objects of type function_base may not be created directly. - -

bool empty() const -

    -
  • Returns: true if the function object has a target, false otherwise.
  • -
  • Throws: will not throw.
  • -
  • Complexity: constant.
  • -
- -

operator bool() const -

    -
  • Returns: !empty()
  • -
  • Throws: will not throw.
  • -
  • Complexity: constant.
  • -
- -

Class template functionN

-

Class template functionN is actually a family of related classes function0, function1, etc., up to some implementation-defined maximum. In this context, N refers to the number of parameters and f refers to the implicit object parameter. - -

functionN(); -

    -
  • Postconditions: f.empty().
  • -
  • Throws: will not throw.
  • -
  • Complexity: constant.
  • -
- -

functionN(const functionN& g); -

    -
  • Postconditions: f contains a copy of the g's target, if it has one, or is empty if g.empty(). The mixin for the f is copy-constructed from the mixin of g.
  • -
  • Complexity: constant.
  • -
- -

template<typename F> functionN(const F& g); -

    -
  • Requires: g is a compatible function object.
  • -
  • Postconditions: f targets a copy of g.
  • -
  • Complexity: constant.
  • -
  • Rationale: g is a reference-to-const because it is a portable, efficient, and concise way to accept any function object or function pointer. In the case of a function pointer, the type of g is reference-to-const pointer-to-function.
  • -
- -

functionN& operator=(const functionN& g); -

    -
  • Postconditions: f targets a copy of g's target, if it has one, or is empty if g.empty(). The mixin for f is assigned the value of the mixin for g.
  • -
  • Returns: *this.
  • -
  • Throws: TBD: Should meet strong guarantee, but doesn't yet.
  • -
  • Complexity: constant.
  • -
- -

template<typename F> functionN& operator=(const F& g); -

    -
  • Requires: g is a compatible function object.
  • -
  • Postconditions: f targets a copy of g.
  • -
  • Returns: *this.
  • -
  • Throws: TBD: Should meet strong guarantee, but doesn't yet.
  • -
  • Complexity: constant.
  • -
  • Rationale: g is a reference-to-const because it is a portable, efficient, and concise way to accept any function object or function pointer. In the case of a function pointer, the type of g is reference-to-const pointer-to-function.
  • -
- -

void set(const functionN& g); -

    -
  • Effects: *this = g.
  • -
- -

template<typename F> void set(const F&); -

    -
  • Effects: *this = g.
  • -
- -

void swap(functionN& g); -

    -
  • Effects: interchanges the targets of f and g.
  • -
  • Throws: will not throw.
  • -
  • Complexity: constant.
  • -
- -

void clear(); -

    -
  • Effects: If !empty(), deallocates current target.
  • -
  • Postconditions: empty().
  • -
  • Complexity: constant.
  • -
- -

result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN); -

    -
  • Requires: !empty().
  • -
  • Effects: target is the underlying function target. It is not const or volatile qualified. -
      -
    1. policy_type policy;
    2. -
    3. policy.precall(this);
    4. -
    5. target(a1, a2, ..., aN);
    6. -
    7. policy.postcall(this);
    8. -
    -
  • Returns: the value returned by target.
  • -
  • Complexity: constant.
  • -
- -

result_type operator()(Arg1 a1, Arg2 a2, ..., ArgN aN) const; -

    -
  • Requires: !empty().
  • -
  • Effects: const-target is the underlying function target. It is const qualified but not volatile qualified. -
      -
    1. policy_type policy;
    2. -
    3. policy.precall(this);
    4. -
    5. const-target(a1, a2, ..., aN);
    6. -
    7. policy.postcall(this);
    8. -
    -
  • Returns: the value returned by const-target.
  • -
  • Complexity: constant.
  • -
- -

Class template function

-

Class template function is a thin wrapper around the numbered class templates function0, function1, etc. It accepts up to MAX_ARGS arguments, but when passed N arguments it will derive from functionN specialized with the arguments it receives. - -

The semantics of all operations in class template function are equivalent to that of the underlying functionN object, although additional member functions are required to allow proper copy construction and copy assignment of function objects. - -

Operations on function object wrappers

-

-

-template<typename ResultType,
-         typename Arg1,
-	 typename Arg2,
-         ...
-	 typename ArgN,
-         typename Policy,
-         typename Mixin,
-         typename Allocator>
-inline void swap(const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>& f,
-                 const function<Arg1, Arg2, ...ArgN, Policy, Mixin, Allocator>& g);
-
-
    -
  • Effects: f.swap(g);
  • -
- -

-

-template<typename ResultType,
-         typename Arg1,
-	 typename Arg2,
-         ...
-	 typename ArgMAX_ARGS>
-inline void swap(const function<Arg1, Arg2, ...ArgMAX_ARGS>& f,
-                 const function<Arg1, Arg2, ...ArgMAX_ARGS>& g);
-
-
    -
  • Effects: f.swap(g);
  • -
- -

Basic usage

-

A wrapper is defined simply by instantiating the function class template with the desired return type and argument types. Any number of arguments may be supplied, up to some implementation-defined limit (10 is the default maximum). The following declares a function object wrapper f that takes two int parameters and returns a float: -

-boost::function<float, int, int> f;
-
- -

By default, function object wrappers are empty, so we can create a -function object to assign to f: -

-struct int_div { float operator()(int x, int y) const { return ((float)x)/y; }; };
-f = int_div();
-
- -

Now we can use f to execute the underlying function object -int_div: -

-  std::cout << f(5, 3) << std::endl;
-
- -

We are free to assign any compatible function object to f. If int_div had been declared to take two long operands, -the implicit conversions would have been applied without any user interference. - -

Invoking a function object wrapper that does not actually contain a function object is a precondition violation. We can check for an empty function object wrapper by querying its empty() method or, more succinctly, by using it in a boolean context: if it evaluates true, it contains a function object target, i.e., -

-  if (f)
-    std::cout << f(5, 3) << std::endl;
-  else
-    std::cout << "f has no target" << std::endl;
-
- -

We can clear out a function target using the clear() member functor. - -

Free functions

-

Free function pointers can be considered singleton function objects with const function call operators, and can therefore be directly used with the function object wrappers: -

-  float mul_ints(int x, int y) { return ((float)x) * y; }
-  f = &mul_ints;
-
- -

Member functions

- -

In many systems, callbacks often call to member functions of a particular -object. Handling argument binding is beyond the scope of Boost.Function. However, there are several libraries that perform 'argument binding', including -

- -

The function family

-

The header <boost/function.hpp> defines the primary entry point to the function object wrappers, the class template boost::function. This class template is essentially a thin wrapper around a set of similar numbered function object wrappers, boost::function0, boost::function1, etc., where the number indicates the number of arguments passed to the function object target. The declaration of f above could also be written as: -

-boost::function2<float, int, int> f;
-
- -

The numbered class templates contain most of the implementation and are each distinct class templates. They may be helpful if used in shared libraries, where the number of arguments supported by Boost.Function may change between revisions. Additionally, some compilers (e.g., Microsoft Visual C++ 6.0) have been known to be incapable of compiling boost::function in some instances but are able to handle the numbered variants. - -

Advanced usage

-

The boost::function family supports additional customization by means of policies, mixins, and allocators. The specific usage of each of these will be explained in later sections, but they share a common problem: how to replace each default with your own version. - -

With boost::function it is not so clear, because support for an arbitrary number of parameters means that it is impossible to specify just the last parameter, but not 5 of the parameters in between. Therefore, boost::function doubles as a generative interface for the underlying numbered class templates that uses named template parameters. For instance, to specify both a policy and an allocator for a function object wrapper f taking an int and returning an int, use: -

-  function<int, int>::policy<MyPolicy>::allocator<MyAllocator>::type f;
-
- -

The named template parameters policy, mixin and allocator each take one template parameter (the replacement class) and may be nested as above to generate a function object wrapper. The ::type at the end accesses the actual type that fits the given properties. - -

Policies

-

Policies define what happens directly before and directly after an invocation of a function object target is made. A policy must have two member functions, precall and postcall, each of which must be able to accept a const function object wrapper pointer. The following policy will print "before" prior to execution and "after" afterwards: - -

-struct print_policy {
-  void precall(const boost::function_base*) { std::cout << "before"; }
-  void postcall(const boost::function_base*) { std::cout << "after"; }
-};
-
- -

A new instance of the policy class will be created prior to calling the function object target and will be preserved until after the call has returned. Therefore, for any invocation the precall and postcall will be executed on the same policy class instance; however, policy class instances will not be kept between target invocations. - -

Policies are further described in the Boost discussion on generic programming techniques. - -

Mixins

-

The function object wrappers allow any class to be "mixed in" as a base class. This allows extra members and/or functionality to be included by the user. This can be used, for instance, to overcome the limitations of policies by storing data between invocations in a base class instead of in a static member of a policy class. - -

Allocators

-

The function object wrappers allow the user to specify a new allocator to handle the cloning of function object targets (when the wrappers are copied). The allocators used are the same as the C++ standard library allocators. The wrappers assume the allocators are stateless, and will create a new instance each time they are used (because they are rebound very often). This shares the semantics of most standard library implementations, and is explicitly allowed by the C++ standard. - -

Example: Synchronized callbacks

-

Synchronization of callbacks in a multithreaded environment is extremely important. Using mixins and policies, a Boost.Function object may implement its own synchronization policy that ensures that only one thread can be in the callback function at any given point in time. - -

We will use the prototype Boost.Threads library for its recursive_mutex. Since the mutex is on a per-callback basis, we will add a mutex to the boost::function by mixin it in with this mixin class: -

-class SynchronizedMixin {
-  mutable boost::recursive_mutex mutex;
-};
-
- -

Next, we create a policy that obtains a lock before the target is called (via the precall function) and releases the lock after the target has been called (via the postcall function): - -

-class SynchronizedPolicy {
-  std::auto_ptr<boost::recursive_mutex::lock> lock;
-
-  void precall(const SynchronizedMixin* f) 
-  {
-    lock.reset(new boost::recursive_mutex::lock(f->mutex));
-  }
-
-  void postcall(const SynchronizedMixin* f)
-  {
-    lock.reset();
-  }
-};
-
- -

The use of std::auto_ptr ensures that the lock will be destroyed (and therefore released) if an exception is thrown by the target function. Now we can use the policy and mixin together to create a synchronized callback: - -

-boost::function2<float, int, int, SynchronizedPolicy, SynchronizedMixin> f;
-
-

Boost.Function vs. Function Pointers

Boost.Function has several advantages over function pointers, namely: