Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-06-12 11:08:48


On Tuesday 12 June 2001 11:42, you wrote:
> Would something like this:
>
> #include <iostream>
> #include "function.hpp"
> #include "smart_ptr.hpp"
>
> struct defer_base {
> virtual ~defer_base() {}
> virtual void operator()() const = 0;
> };
>
>
> template <typename Ret>
> struct function0 : public defer_base {
> function0(Ret(*Func)()) : f_(Func) {}
> virtual void operator()() const {
> f_();
> }
> boost::function<Ret> f_;
> };
>
> template <typename Ret, typename Type1, typename Parm1>
> struct function1 : public defer_base {
> function1(Ret(*Func)(Type1), Parm1 const & p1)
>
> : f_(Func), p1_(p1) {}
>
> virtual void operator()() const {
> f_(p1_);
> }
> boost::function<Ret, Type1> f_;
> Parm1 p1_;
> };
>
> typedef boost::shared_ptr<defer_base> defer_holder;
>
> template <typename Ret>
> defer_holder defer_call(Ret(*Func)())
> {
> return defer_holder(new function0<Ret>(Func));
> }
>
> template <typename Ret, typename Type1, typename Parm1>
> defer_holder defer_call(Ret(*Func)(Type1), Parm1 const & p1)
> {
> return defer_holder(new function1<Ret, Type1, Parm1>(Func, p1));
> }
>
> void foo()
> {
> std::cout << "Hello there!" << std::endl;
> }
>
> void foo1(int i)
> {
> cout << "Hello " << i << " times!" << endl;
> }
>
> int main()
> {
> defer_holder dh = defer_call(foo);
> (*dh)();
> dh = defer_call(foo1, 42);
> (*dh)();
> }
>
> be interesting for boost?
>
> example above is a bit stupid since it just duplicates function,
> however as the number of parameters rise it gets more interesting.
>
> The above is built from the Functor/DeferCall library in CUJ-May 2001:
> "Elegant Function Call Wrappers" by Andreas Huber, main change is
> usign boost::function internally and passing a
> boost::shared_ptr<defer_base> instead of a defer_base*. (Also references
> are not supported)

Deferring calls and binding arguments are orthogonal (though complementary)
activities and they should be separate libraries. Boost.Function is intended
to handle deferred calls and nothing more. There are other libraries that
bind arguments - the Lambda library (http://lambda.cs.utu.fi/) is one such
library, and I though someone was working on a more lightweight binding
library for Boost...

You example above, with Boost.Function and a binders library, would be:

function<void> dh = foo;
dh();
dh = bind(foo, 42);
dh();

        Doug


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk