Boost logo

Boost :

From: Eric Niebler (neric_at_[hidden])
Date: 2003-10-05 22:47:45

In this month's CUJ, Anson Tsao of Microsoft and I describe one approach
to implementing a FOR_EACH macro that makes it easy to loop over .NET
collections in managed C++. I have reimplemented the code from scratch
to work only with native types.

You can use it as follows to loop over an STL collection, for example:

std::list<int> int_list;
BOOST_FOREACH( int &i, int_list )
     // mutates the int in the list:
     i += 20;
     // break works as you would expect
     if ( i == 100 )

It has several advantages over std::for_each. In particular:
   - You don't have to define a predicate at namespace scope
   - You can break, continue, goto or return from the middle
     of the loop body.
   - In the loop body, you have complete access to the local
     variables from the surrounding code.
   - You don't need to worry about off-by-one errors, iterators,
     half-open sequences, binders, adapters, lambdas....

It has a few advantages over the implementation described in the CUJ
   - It works with dependent types
   - It takes only 2 parameters, instead of 3
   - It doesn't require partial template specialization for reference
     loop variables
   - It is safer because it detects when the container is not an lvalue.
   - The code is much cleaner and shorter.

I have uploaded the new implementation to:

Right now, the code is self-contained, but if there is interest, I can
boost-ify it by making use of boost::enable_if and
boost::container_traits, once they are available.

I have tested the code on VC7, VC7.1, gcc 3.2 on linux and cygwin on

So, any interest?


P.S. If you'd like to look at the older implementation for the CUJ, you
can find it here:

Boost list run by bdawes at, gregod at, cpdaniel at, john at