Boost logo

Boost Users :

Subject: Re: [Boost-users] [bind] How to dereference _1 in a boost::bind expression
From: Sven Gaerner (sgaerner_at_[hidden])
Date: 2008-10-02 10:12:49


On Thu, 2 Oct 2008 14:36:01 +0100
"Peter Barker" <newbarker_at_[hidden]> wrote:

> On Thu, Oct 2, 2008 at 11:45 AM, Sven Gaerner <sgaerner_at_[hidden]>
> wrote:
> > On Thu, 2 Oct 2008 11:12:54 +0100
> > "Peter Barker" <newbarker_at_[hidden]> wrote:
> >
> >> Hello,
> >>
> >> Here's an example of my problem:
> >>
> >> #include <algorithm>
> >> #include <vector>
> >>
> >> #include <boost/bind.hpp>
> >>
> >> class TheClass
> >> {
> >> };
> >>
> >> void accept(TheClass& tc)
> >> {
> >> }
> >>
> >> int main()
> >> {
> >> std::vector<TheClass*> cont;
> >>
> >> // Compile error - how to dereference _1 ???
> >> std::for_each(cont.begin(),cont.end(),boost::bind(&accept,_1));
> >> }
> >>
> >> How can I dereference _1 so I can use the accept function?
> >>
> >> Regards,
> >>
> >> Pete
> >> _______________________________________________
> >> Boost-users mailing list
> >> Boost-users_at_[hidden]
> >> http://lists.boost.org/mailman/listinfo.cgi/boost-users
> >>
> >
> > You don't have to dereference _1. Your accept function must look
> > like this:
> > void accept(TheClass *arg) {
> > }
> > Your std::vector contains pointers to TheClass so std::for_each()
> > passes objects of that type to your functor, in this case a
> > pointer to types of TheClass.
>
> Sven,
>
> I was trying to avoid changing the signature of accept as it has other
> call sites and I would need to update them. It's what I did in the end
> though. Thanks,
>
> Pete
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>

Peter,

I didn't think about avoiding to change the signature. Sorry for that.

What about using a specific delegate functor? Somethink like that:

struct Delegate {
 void operator()(TheClass *arg) {
   accept(*arg);
 }
};

And then pass this functor to std::for_each();

std::for_each(cont.begin(),cont.end(), Delegate());

That wouldn't break the signature of the accept function, but it
depends on that particular implementation.

Sven


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