Pete Bartlett wrote:
#define REVERSE_FOREACH( x , container ) BOOST_FOREACH( x , make_reverse_iterator_range( container ) )
Something like this is what I was going to suggest, but ...
This works fine when container is an lvalue. But then co-workers, used to the wonders of the original FOREACH, inevitably start to use the new macro with rvalues and get a crash due to dangling references (– the iterator_range’s members point to departed quantities…..)
... ouch. If the container is an rvalue, it will be copied by FOREACH, but it the "container" is really just a proxy (eg., an iterator pair) to a temporary object, then copying the proxy doesn't help you, as you've discovered. <snip>
… but all these issues are exactly the ones that BOOST_FOREACH itself solves! Thus surely it is technically possible to write a REVERSE_FOREACH that works with rvalues as well as lvalues, e.g. by essentially copying and pasting the FOREACH implementation and replacing “begin” and “end” by “rbegin” and “rend” in the vital places.
Yes. However
one feels there may be a better way… has anyone had a go at creating a “fully-functional” REVERSE_FOREACH and could offer me any advice? If indeed the task is fairly intricate and requires re-use of foreach internals, would the library author consider including something in the library itself?
You're not the first to want a REVERSE_FOREACH, but this is the first legitimate argument I've heard for it. Could you go to http://svn.boost.org/trac and open a new ticket there. Make the ticket type "feature request" and the component "foreach". I'll look into it when I have a chance. -- Eric Niebler Boost Consulting www.boost-consulting.com