Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-02-20 20:19:21


Trey Jackson wrote:
> Just started using boost::bind, like it a lot.
> I'm playing around with a little work crew,
> which just queues up data, then calls the function
> on them later.

[...]

> I'd like to be able to do something like:
> ,----------------
> | work_crew<???> mycrew(bind(&X::f, &x, _1, _2));
> |
> | mycrew.add( ?? 9 10 ?? );
> | mycrew.add( ?? 42 10 ?? );
> | mycrew.add( ?? 29232 10 ?? );
> |
> | // do work
> | mycrew.dowork(); // STILL calls x.f(9, 10), x.f(42,10),
> x.f(29232,10)b
> `----------------
>
>
> Where obviously I have to do something special to package up the
> arguments to the function object that's been created.
>
>
> Is it possible without a huge amount of coding?

I was doing something like it recently, so, sure:

#include "boost/function.hpp"
#include "boost/bind.hpp"
#include "boost/tuple/tuple.hpp"
#include "boost/tuple/apply.hpp"

#include <list>

using namespace boost;

template <class DataType, class FunctionType = boost::function1<void,
DataType> >
class work_crew {
  std::list<DataType> queue_;
  FunctionType engine_;
public:
  work_crew(FunctionType const& tocall);
  void add(DataType d) { queue_.push_front(d); };
  void dowork()
  {
    typedef typename std::list<DataType>::iterator iterator_t;
    for (iterator_t iter = queue_.begin(); iter != queue_.end(); ++iter)
       tuples::apply(this->engine_, *iter); // here
  };
};

struct X {
    bool f(int a, int b);
};

X x;

int main()
{
    work_crew< tuples::tuple<int,int>, boost::function2<void,int,int> >
        mycrew(bind(&X::f, &x, _1, _2));

    mycrew.add( tuples::make_tuple(9, 10) );
    mycrew.add( tuples::make_tuple(42, 10) );
    mycrew.add( tuples::make_tuple(29232, 10) );

    // do work
    mycrew.dowork(); // STILL calls x.f(9, 10), x.f(42,10), x.f(29232,10)b
}

With a little bit more of coding and Boost.MPL, you can do even better on

    work_crew< tuples::tuple<int,int>, boost::function2<void,int,int> >
        mycrew(bind(&X::f, &x, _1, _2));

line:

    work_crew< mpl::list<int,int> > mycrew(bind(&X::f, &x, _1, _2));

but I am not sure if you want to dive into it from the beginning.

The only caveat to the above is that "tuple/apply.hpp" header is not a part
of the Boost yet. Please see
http://www.mail-archive.com/boost@lists.boost.org/msg05246.html for the
source.

We still have a chance to have the facility in 1.30 release, though (it's a
pure extension of Boost.Tuple library) - but I need to hear from Jaakko on
this one.

Aleksey


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