Boost logo

Boost :

From: larsbj_at_[hidden]
Date: 2001-06-12 10:42:00


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)

-- 
	Lgb

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