Boost logo

Boost :

From: Shane Beasley (sbeasley_at_[hidden])
Date: 2002-09-16 23:21:39


This is less of a practical matter and more of an intellectual exercise,
but I thought it was intriguing...

I have a std::map<K, Foo> over which I wish to iterate, using STL and
Boost templates to call a non-const member function on each Foo object.
The solution would appear to be something like

  std::for_each(m.begin(), m.end(), func);

where func(x) would call x.second.mem_fun(). The trouble is defining func
in terms of STL and Boost components. Two possible roads to a solution
come to mind, but I can't get either to work without significant outside
assistance. The idea is to maximize code reuse, for no other reason than
that I'd rather waste time trying to use other people's code than trying
to rewrite other people's code. :)

(a) In theory, I should be able to use compose_f_gx, where g(x) will
return the Foo object x.second and f(g(x)) will apply the member function
to that Foo object. Unfortunately, compose_f_gx takes x as a const
reference, forcing g to return a const reference, thus preventing f from
applying a non-const member function to the result.

I'm thinking that this problem could be solved easily by adding another
operator() to compose_f_gx which takes a non-const reference -- what do
you think about this?

(b) Use boost::lambda to do something similar to the above. Unfortunately,
I cannot see any way for boost::lambda to emulate the functionality of
compose_f_gx; bind(f, g, x) is f(g, x), which isn't very useful here.

Incidentally, it would be nice to be able to use boost::lambda to access a
member field through a reference; unfortunately, it seems to be able to do
so through pointers only, not references. Am I missing something, e.g.,
can I get a pointer from a reference, then call something on it? This
sounds like another case of compose_f_gx (where g(x) is &x and f(g(x))
is (&x)->second).

Any suggestions would be appreciated.

Regards,

Shane Beasley


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk