Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2003-10-09 14:05:29


Resending. Based on the number of private replies I got, I suspect there
is some interest in adding a foreach looping construct to Boost. The
lack of public discussion makes me wonder, though. Does no one want to
publically support an Ugly Macro? :-) Or is this just not compelling enough?

To recap, I'm suggesting the addition of BOOST_FOREACH to make it
trivial to write loops over sequences and containers of various sorts.

Typical usage:
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 )
          break;
}

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com
Eric Niebler wrote:
> 
> 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 )
>         break;
> }
> 
> 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 
> article:
>   - 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:
> http://groups.yahoo.com/group/boost/files/BOOST_FOREACH/
> 
> 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 
> windows.
> 
> So, any interest?
> 
> Eric
> 
> P.S. If you'd like to look at the older implementation for the CUJ, you 
> can find it here: ftp://ftp.cuj.com/pub/2003/2111/nieblerTsao.zip
> 
> 
> _______________________________________________
> Unsubscribe & other changes: 
> http://lists.boost.org/mailman/listinfo.cgi/boost
> 

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