Boost logo

Boost Users :

From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2006-03-30 03:57:47


On 3/30/06, Nico Galoppo <nico_at_[hidden]> wrote:
<snip>
>
> Well, I probably over-simplified the problem. What I would really like to do is
> manipulate data members of all instances in a container, where the data member
> is given as an input parameter.
>
> struct A {
> int value;
> int othervalue;
> }
>
> container<A> array;
>
> void f(container<A> & array, membervarref)
> {
> BOOST_FOREACH(container<A>::value_type& element, array)
> bind(membervarref, element) = 3;
> }
>
> f(array, &A::value);
> f(array, &A::othervalue);
>
> --nico
>

Well, how about this (using you definition of A):

typedef std::vector<A> As;
typedef int A::*Setter;

void Set(As& as, Setter setter, int value)
{
   using namespace boost::lambda;
   std::for_each(as.begin(), as.end(), bind(setter, _1) = value);
}

void func()
{
   As as;

   Set(as, &A::a, 3);
   Set(as, &A::b, 5);
}

If you want to decouple from A a bit more, you could change the
definition of Setter like below

typedef boost::function<int&(A&)> Setter;

and it'll compile and run OK (tested with VC7.1).

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