Boost logo

Boost Users :

From: Edward Diener (eddielee_at_[hidden])
Date: 2002-08-13 08:14:04


"Albrecht Fritzsche" <albrecht.fritzsche_at_[hidden]> wrote in message
news:3D58B5C7.1080008_at_tiscali-dsl.de...
> Edward Diener wrote:
> >>class Publisher {
> >> typedef boost::function<void> Function;
> >>public:
> >> void SetChecker(const Function& Callback){ }
> void Publish(){}
> >>};
> >>
> >>class Manager {
> >>public:
> >> Manager();
> >>private:
> >> void Check() {}
> >>};
> >>
> >>Manager::Manager()
> >>{
> >> Publisher d;
> >> d.SetChecker(std::mem_fun(&Manager::Check));
>
> > try:
> > d.SetChecker(boost::bind(&Manager::Check,this));
>
> Brilliant - thanks! Would you mind giving me a short
> rationale about this, since I am a newbie regarding
> function pointers and function (object?) adaptors.
>
> SO, if using an stl algorithm like
>
> vector<Publisher> p;
> for_each(p.begin(), p.end(), mem_fun(&Publisher::Publish));
>
> I don't have to bind anything, do I? mem_fun() returns a
> mem_fun_t functor object, which will receive the Publisher
> object pointer through each intern for_each call?

The function adaptor which mem_fun becomes takes a pointer or reference to
its type as its single argument in order to call the member function. The
for_each algorithm passes such a reference to each type in its internal
loop, so everything is in sync.

>
> And that object pointer passing was missing in my code and
> was achieved in your code through the binding?

In the boost::bind case, for a member function, you need to bind in a
pointer to the actual object, which passing the "this" parameter does
effectively. You don't need mem_fun with boost::bind, ie.

d.SetChecker(boost::bind(std::mem_fun(&Manager::Check),this));

since boost::bind is smart and automatically knows how to bind member
functions.

> I had already
> looked at boost::bind but still cannot figure out its interface
>
> template<class F, class A1> unspecified-3-1 bind(F f, A1 a1);
>

I have already mentioned to Peter Dimov that the doc for boost::bind might
be updated to be more easily understandable. The boost::bind syntax creates
a function adaptor, which is what boost::function wants. It is a much
smarter version of the C++ standard library's std::bind1st and std::bind2nd
with, more or less, unlimited parameters and types. I suggest you first look
at the standard library versions and then re-read boost::bind documentation.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net