Boost logo

Boost Users :

From: Joel de Guzman (joel_at_[hidden])
Date: 2005-07-18 23:25:25


Edson Tadeu wrote:
> I'm trying to learn to use Phoenix, but I haven't found an example of
> how to do the following simple thing using its inline lazy function
> creation (it seems that there isn't a simple way to do this):
>
> struct Test {
> int x;
> void Test() {x = 1;}
> void inc(int i) { x += i; }
> };
>
> void main() {
> vector<Test> v;
> v.resize(5);
>
> // v == {1, 1, 1, 1, 1}
>
> for_each(v.begin(), v.end(), arg1.inc(1 + arg1.x) )
>
> // v == {3, 3, 3, 3, 3}
> }
>
>
> The only ways I found to do this involves function<> that needs an
> external functor declaration, but this is ugly just like old STL
> functors, or using member_function_ptr and member_var_ptr templates,
> but I couldn't get them to work on Borland C++.
>
> Anyone knows how to do it, keeping simplicity and elegance?

Bind is your friend:

     for_each(v.begin(), v.end(),
         bind(&Test::inc, arg1, 1 + bind(&Test::x, arg1));

This syntax assumes Phoenix-2. Alas, Borland is no longer
supported. I guess your only option now is to use boost::bind.
The syntax should be the same, except that arg1 is _1.

Regards,

-- 
Joel de Guzman
http://www.boost-consulting.com
http://spirit.sf.net

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