Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2005-05-02 10:10:35


Andy Little wrote:
>
>
> I have used the BOOST_FOREACH macro and its ok. As its main raison
> d'aitre is brevity, why do I need to explicitly provide the loop
> variable.I would hope for something like:
>
> FOREACH(my_container){ std::cout << *_ << '\n'; }
>
> IOW the boost::lambda placeholders could be used.

What about nested invocations for BOOST_FOREACH:

     int a[100][200];
     int sum = 0;

     BOOST_FOREACH(int (&x)[200], a)
         BOOST_FOREACH(int i, x)
             sum += i;

?

> I dont know of a reason to require conversions as in the example:
> short array_short[] = {1,2,3};
> BOOST_FOREACH( int i, array_short )
> {
> // The short was implicitly converted to an int
> }
> What is the point of the example?

Conversions aren't "required", they are allowed. The point is to show
that the loop variable doesn't have to have the same type as the element
type, it only must be convertible.

> FWIW A naive method to do the above is as:
>
> #define FOR_EACH(cont) \
> for (BOOST_TYPEOF( cont )>::iterator _ = cont ## .begin();\
> _ != cont ## .end();\
> ++ _ )
>
> exept require *_ as opposed to _
>
> However maybe this is an advantage... because the iterator is exposed
> then more loop information is avaialable eg if _ ==
> my_container::begin() etc., which is an advantage over simply having the
> element available so making things more versatile.
>

It makes BOOST_FOREACH harder to extend. Not every sequence that users
may want to iterate has anything like an iterator which is
dereferencable. It is currently possible to make such non-STL sequences
work with FOREACH with little effort, but after this change it would be
impossible.

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com

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