To read all comments associated with this story, please click here.
> and it doesn't require the compiler to support typeof
> or auto, so it works on older compilers. It even allows
> you to mutate the sequence in place:
Well, looking at the code you pasted it avoids using a the typeof or the auto keywords because it requires you to write the type of the iterator explicitely. This means that BOOST's foreach isn't polymorphic per se. You must admit my implementation is nicer 
Looking at the code of BOOST's foreach, I see it has a lot of code before the real for loop, which makes it impossible to use BOOST_FOREACH the same way you would use for(), forcing you to wrap it up between braces, in some circumstances.
It's also true that my implementation has the pitfall that it may evaluate the arguments more than once, though. Well, to solve these issues c++ should let the user define her own keywords... perhaps one day 





Member since:
2005-06-29
A foreach looping macro was recently accepted into Boost ( http://boost.org ). It works with STL containers, arrays, and iterator ranges, and it doesn't require the compiler to support typeof or auto, so it works on older compilers. It even allows you to mutate the sequence in place:
int array[] = {1,2,3,4};
BOOST_FOREACH(int & i, array)
{
++i;
}
// array is now {2,3,4,5}
The docs are at http://boost-sandbox.sf.net/libs/foreach .
You can download the code (foreach.zip) at http://boost-sandbox.sf.net/vault/index.php?directory=eric_niebler .
The code requires Boost 1.32.
--
Eric Niebler
Boost Consulting
http://www.boost-consulting.com