Boost logo

Boost Users :

Subject: Re: [Boost-users] What's wrong with my use of member-function bind?
From: Nathan Ridge (zeratul976_at_[hidden])
Date: 2011-07-28 04:50:31


> Thanks. Can someone tell me what's wrong? I thought I followed the
> example from the manual.
>
>
> void foo (int);
>
>
> class S {
> const char* const name;
> public:
> S(const char* x) : name(x) {}
> void bar (int);
> };
>
>
>
> S s1 ("s1"); // some instance
>
> void subscribe (State_t st, const NotifyFunc& func);
>
> subscribe (STATE1, &foo); // this works, so the form of the function
> parameters is right.
>
> subscribe (STATE1, bind(&S::bar, &s1)); // this one is wrong. Why?
>
>
> Does
>
> subscribe (STATE1, bind(&S::bar, s1));
>
> work?

No, you need to do bind(&S::bar, s1, _1).
 
The _1 in this case means "pass the FIRST argument given to the
result of the bind (FIRST because it's _1), as the SECOND argument
to &S::bar (SECOND because the _1 appeared as the second argument
to bind(), after the function itself). Note that as a member
function, bind considers the first argument of &S::bar to be the
object on which the member function is called.
 
In other words, if
 
f = bind(&S::bar, s1, _1)
 
then f(x) is equivalent to bar(s1, x) (which is really s1.bar(x)).
 
If you just do
 
f = bind(&S::bar, s1)
 
then f(x) will just be equivalent to bar(s1) (i.e. s1.bar())
(the x will just be ignored), but that is not a valid way to call
&S::bar, so it's an error.
 
Regards,
Nate.


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