forked from boostorg/function
168 lines
10 KiB
HTML
168 lines
10 KiB
HTML
![]() |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
||
|
<html>
|
||
|
<head>
|
||
|
<title>Boost.Function Tutorial</title>
|
||
|
</head>
|
||
|
|
||
|
<body bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080">
|
||
|
|
||
|
<h1><IMG SRC="../../../c++boost.gif" WIDTH="276" HEIGHT="86">Boost.Function Tutorial</h1>
|
||
|
|
||
|
<h2><a name="usage">Basic usage</a></h2>
|
||
|
<p> A function wrapper is defined simply by instantiating the <code>function</code> 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 <code>f</code> that takes two <code>int</code> parameters and returns a <code>float</code>:
|
||
|
<pre>
|
||
|
boost::<a href="reference.html#function">function</a><float, int, int> f;
|
||
|
</pre>
|
||
|
|
||
|
<p> By default, function object wrappers are empty, so we can create a
|
||
|
function object to assign to <code>f</code>:
|
||
|
<pre>
|
||
|
struct int_div {
|
||
|
float operator()(int x, int y) const { return ((float)x)/y; };
|
||
|
};
|
||
|
|
||
|
f = int_div();
|
||
|
</pre>
|
||
|
|
||
|
<p> Now we can use <code>f</code> to execute the underlying function object
|
||
|
<code>int_div</code>:
|
||
|
<pre>
|
||
|
std::cout << f(5, 3) << std::endl;
|
||
|
</pre>
|
||
|
|
||
|
<p> We are free to assign any compatible function object to <code>f</code>. If <code>int_div</code> had been declared to take two <code>long</code> 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:
|
||
|
<pre>
|
||
|
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;
|
||
|
</pre>
|
||
|
|
||
|
<p> 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 <code><a href="reference.html#empty">empty</a>()</code> method or, more succinctly, by using it in a boolean context: if it evaluates true, it contains a function object target, i.e.,
|
||
|
<pre>
|
||
|
if (f)
|
||
|
std::cout << f(5, 3) << std::endl;
|
||
|
else
|
||
|
std::cout << "f has no target, so it is unsafe to call" << std::endl;
|
||
|
</pre>
|
||
|
|
||
|
<p> We can clear out a function target using the <code><a href="reference.html#functionN_clear">clear</a>()</code> member function.
|
||
|
|
||
|
<h3>Free functions</h3>
|
||
|
<p> 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:
|
||
|
<pre>
|
||
|
float mul_ints(int x, int y) { return ((float)x) * y; }
|
||
|
f = &mul_ints;
|
||
|
</pre>
|
||
|
|
||
|
<h3>Member functions</h3>
|
||
|
<a name="member_func">
|
||
|
<p> 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
|
||
|
<ul>
|
||
|
<li> The C++ Standard library. Using <code>std::bind1st</code> and <code>std::mem_fun</code> together one can bind the object of a pointer-to-member function for use with Boost.Function:
|
||
|
<pre>
|
||
|
struct X {
|
||
|
int foo(int);
|
||
|
};
|
||
|
|
||
|
boost::function<int, int> f;
|
||
|
X x;
|
||
|
f = std::bind1st(std::mem_fun(&X::foo), &x);
|
||
|
|
||
|
f(5); // Call x.foo(5)</pre></li>
|
||
|
|
||
|
<li><a href="http://lambda.cs.utu.fi/">The Lambda library</a>. This library provides a powerful composition mechanism to construct function objects that uses very natural C++ syntax. Lambda requires a compiler that is reasonably conformant to the C++ standard. Note that it is not a Boost library.</li>
|
||
|
|
||
|
<li>Peter Dimov's <a href="http://groups.yahoo.com/group/boost/files/bind/bind.hpp">bind</a> library. It has a smaller scope than the Lambda Library but is more tolerant of broken compilers. It is an unreviewed library in development.</li>
|
||
|
</ul>
|
||
|
|
||
|
<h2><a name="family">The <code>function</code> family</a></h2>
|
||
|
<p> The header <<a href="../../boost/function.hpp">boost/function.hpp</a>> defines the primary entry point to the function object wrappers, the class template <code>boost::function</code>. This class template is essentially a thin wrapper around a set of similar numbered function object wrappers, <code>boost::function0</code>, <code>boost::function1</code>, etc., where the number indicates the number of arguments passed to the function object target. The declaration of <code>f</code> above could also be written as:
|
||
|
<pre>
|
||
|
boost::function2<float, int, int> f;
|
||
|
</pre>
|
||
|
|
||
|
<p> 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 <code>boost::function</code> in some instances but are able to handle the numbered variants.
|
||
|
|
||
|
<h2><a name="advanced">Advanced usage</a></h2>
|
||
|
<p> The <code>boost::function</code> 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.
|
||
|
|
||
|
<p> With <code>boost::function</code> 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, <code>boost::function</code> 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 <code>f</code> taking an <code>int</code> and returning an <code>int</code>, use:
|
||
|
<pre>
|
||
|
function<int, int>::policy<MyPolicy>::allocator<MyAllocator>::type f;
|
||
|
</pre>
|
||
|
|
||
|
<p> The named template parameters <code>policy</code>, <code>mixin</code> and <code>allocator</code> each take one template parameter (the replacement class) and may be nested as above to generate a function object wrapper. The <code>::type</code> at the end accesses the actual type that fits the given properties.
|
||
|
|
||
|
<h3><a name="policies">Policies</a></h3>
|
||
|
<p> 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, <code>precall</code> and <code>postcall</code>, each of which must be able to accept a <code>const</code> function object wrapper pointer. The following policy will print "before" prior to execution and "after" afterwards:
|
||
|
|
||
|
<pre>
|
||
|
struct print_policy {
|
||
|
void precall(const boost::function_base*) { std::cout << "before"; }
|
||
|
void postcall(const boost::function_base*) { std::cout << "after"; }
|
||
|
};
|
||
|
</pre>
|
||
|
|
||
|
<p> 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 <code>precall</code> and <code>postcall</code> will be executed on the same policy class instance; however, policy class instances will not be kept between target invocations.
|
||
|
|
||
|
<p> Policies are further <a href="../../../more/generic_programming.html#policy">described</a> in the Boost discussion on <a href="../../../more/generic_programming.html">generic programming techniques</a>.
|
||
|
|
||
|
<h3><a name="mixins">Mixins</a></h3>
|
||
|
<p> 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 <code>static</code> member of a policy class.
|
||
|
|
||
|
<h3><a name="allocators">Allocators</a></h3>
|
||
|
<p> 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.
|
||
|
|
||
|
<h3><a name="synchronizing">Example: Synchronized callbacks</a></h3>
|
||
|
<p> 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.
|
||
|
|
||
|
<p> We will use the prototype Boost.Threads library for its <code>recursive_mutex</code>. Since the mutex is on a per-callback basis, we will add a mutex to the <code>boost::function</code> by mixin it in with this mixin class:
|
||
|
<pre>
|
||
|
class SynchronizedMixin {
|
||
|
mutable boost::recursive_mutex mutex;
|
||
|
};
|
||
|
</pre>
|
||
|
|
||
|
<p> Next, we create a policy that obtains a lock before the target is called (via the <code>precall</code> function) and releases the lock after the target has been called (via the <code>postcall</code> function):
|
||
|
|
||
|
<pre>
|
||
|
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();
|
||
|
}
|
||
|
};
|
||
|
</pre>
|
||
|
|
||
|
<p>The use of <code>std::auto_ptr</code> 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:
|
||
|
|
||
|
<pre>
|
||
|
boost::function2<float, int, int, SynchronizedPolicy, SynchronizedMixin> f;
|
||
|
</pre>
|
||
|
|
||
|
<hr>
|
||
|
<address><a href="mailto:gregod@cs.rpi.edu">Douglas Gregor</a></address>
|
||
|
<!-- Created: Fri Jul 13 12:47:11 EDT 2001 -->
|
||
|
<!-- hhmts start -->
|
||
|
Last modified: Fri Jul 13 23:58:17 EDT 2001
|
||
|
<!-- hhmts end -->
|
||
|
</body>
|
||
|
</html>
|