In C++, writing a loop that iterates over a sequence is tedious. We can either
use iterators, which requires a considerable amount of boiler-plate, or we
can use the std::for_each()
algorithm and move our loop body into a predicate, which requires no less boiler-plate
and forces us to move our logic far from where it will be used. In contrast,
some other languages, like Perl, provide a dedicated "foreach" construct
that automates this process. BOOST_FOREACH is just such
a construct for C++. It iterates over sequences for us, freeing us from having
to deal directly with iterators or write predicates.

BOOST_FOREACH is designed for ease-of-use and efficiency.
It does no dynamic allocations, makes no virtual function calls or calls through
function pointers, and makes no calls that are not transparent to the compiler's
optimizer. This results in near-optimal code generation; the performance of
BOOST_FOREACH is usually within a few percent of the equivalent
hand-coded loop. And although BOOST_FOREACH is a macro,
it is a remarkably well-behaved one. It evaluates its arguments exactly once,
leading to no nasty surprises.

BOOST_FOREACH iterates over sequences. But what qualifies
as a sequence, exactly? Since BOOST_FOREACH is built on
top of Boost.Range, it automatically
supports those types which Boost.Range
recognizes as sequences. Specifically, BOOST_FOREACH works
with types that satisfy the Single
Pass Range Concept. For example, we can use BOOST_FOREACH
with:

STL containers

arrays

Null-terminated strings (char
and wchar_t)

std::pair of iterators

Note

The support for STL containers is very general; anything that looks like
an STL container counts. If it has nested iterator
and const_iterator types
and begin()
and end()
member functions, BOOST_FOREACH will automatically know
how to iterate over it. It is in this way that boost::iterator_range<>
and boost::sub_range<>
work with BOOST_FOREACH.

See the section on Extensibility
to find out how to make BOOST_FOREACH work with other types.

People have complained about the name BOOST_FOREACH. It's
too long. ALLCAPS
can get tiresome to look at. That may be true, but BOOST_FOREACH
is merely following the Boost
Naming Convention. That doesn't mean you're stuck with it, though.
If you would like to use a different identifier (foreach,
perhaps), you can simply do:

Only do this if you are sure that the identifier you choose will not cause
name conflicts in your code.

Note

Do not use #defineforeach(x,y)BOOST_FOREACH(x,y). This
can be problematic if the arguments are macros themselves. This would result
in an additional expansion of these macros. Instead, use the form shown above.