Boost logo

Boost Users :

Subject: Re: [Boost-users] [Bind] Is this how to write it?
From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2010-03-23 06:02:08


On Tue, Mar 23, 2010 at 9:49 AM, Robert Jones <robertgbjones_at_[hidden]> wrote:
>
> Hi All
>
> In this bit of code....
>
> #include <algorithm>
> #include <vector>
> #include "boost/bind.hpp"
>
> struct A
> {
>     int double_it( int i ) { return i * 2; }
> } a;
>
> std::vector< int > v;
>
> int main( )
> {
>     for ( std::vector< int >::iterator i = v.begin( ); i != v.end( ); ++ i )
>     {
>         a.double_it( * i );
>     }
>
>     // Write it as a for_each/bind
>     std::for_each( v.begin(), v.end(), boost::bind( & A::double_it, boost::ref( a ), _1 ) );
> }
>
> Is that last line the idiomatic way of writing the bind expression?
>
> Thanks, Rob.
>

Your code is fine when the bound thing is a method - you could use
'&a' rather than 'boost::ref(a)' (a pointer to 'a' can be used for a
method call in place of a reference to 'a')

However, for your 'double_it', I'd personally just write a function
rather than define a struct with a method. Then, 'a' is not needed and
the bind would be:

std::for_each( v.begin(), v.end(), boost::bind( &double_it, _1 ) );

HTH!

Stuart Dootson


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