Boost logo

Boost Users :

Subject: Re: [Boost-users] bind member function of a member of a class...
From: Alan M. Carroll (amc_at_[hidden])
Date: 2009-03-04 18:03:12


That's not a good usage scenario for bind - you should just call the method directly. Bind is useful when you want to either (1) pass the functor to something else or (2) store the functor for future use. Conceptually, as a rough guide, you should think of the result of bind as a pointer, not a value. So, naturally, the result of bind of anything isn't going to be equal to 1, just like you won't have a pointer equal to one. Instead you want to compare the result of invoking / dereferencing the functor, which is done with the function operator (). So your example would work if you added that, e.g.

return (boost::bind (&B::getA::test, b)() ==1);

But a more standard use case would look like (untested)

template < typename F > bool check_property(F const& func, B const& b) {
  return func(b);
}

bool testbind() {
  B b;
  return check_property(boost::bind(&A::test, boost::bind(&B::getA, _1)) == 1, b);
}

The == operator of a bind result and a int creates a functor that compares the result of invoking the functor to that int. This passes that to check_property which invokes it with the function operator.

P.S. If you want to store a Bind result for later use, look at Boost.Function. These two libraries are duals of each other - Bind to *pass* function objects to somebody else, Function to *receive* function objects from somebody else.

At 04:33 PM 3/4/2009, you wrote:
>I cannot figure out how to use boost::bind in following scenario:
>
>class A
>{
> int i_;
>public:
> int test() {return i;}
>};
>
>class B
>{
> A _a;
>public:
> A& getA() {return _a;}
>}
>
>bool testbind()
>{
> B b;
>
> // here I am trying to find out if b.getA().test() equals 1
> // I understand that B::getA::test is incorrect, and that's my question-
> // how to use bind here?
> return (boost::bind (&B::getA::test, b) ==1);
>}
>
>
>
>
>_______________________________________________
>Boost-users mailing list
>Boost-users_at_[hidden]
>http://lists.boost.org/mailman/listinfo.cgi/boost-users


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