The purpose and functioning of std::for_each
is very different from that of the macros BOOST_FOREACH
and Q_FOREACH
.
std::for_each
is, first and foremost, a function call. It is an algorithm. You call it, providing a pair of iterators. On each member of the iterator range, it will call the given function with the value fetched from the iterator in question.
The purpose of std::for_each
, conceptually speaking, is really to match up with the more specific algorithms that already exist. With algorithms like count
, copy
, etc, it makes sense to have one that simply executes arbitrary code for every element.
BOOST_FOREACH
and Q_FOREACH
are equivalent constructs (which I will collectively call FOREACH
), but behave differently from std::for_each
.
FOREACH
is, first and foremost, a for loop. Now, that might not sound so different, but think about it. You cannot call continue
and break
from within std::for_each
. continue
can be emulated easily enough with return
(though this also means you can't return from the function that issues the std::for_each
call). But there's no way to escape from the std::for_each
loop if you want to stop. Similarly, you can't goto
out of a for_each
loop. The best you can do in either case is throw an exception, and that's using exceptions for flow control (ie: not a good idea).
When you use std::for_each
, you must provide some callable function. This could be a function pointer or function object. Because of that, your code is somewhat de-localized. This is fine if what you're doing in each iteration is a complex, multi-line function. But if each iteration's logic is quite simple, then code readability decreases a bit.
FOREACH
executes a local block of code. So the code is right there; you don't have to track down a function to see what's happening on each iteration.
Also, calling a function means having to write that function. If you need to keep track of state, you now need a functor, which requires more code to write.
C++11 makes std::for_each
much more attractive with lambda functions. This removes the code locality problem: the source code is right there. And since lambdas can capture stuff, it can work almost exactly like a regular for
loop. Well, except for no break
functionality, but that's usually avoidable.
Of course, C++11 also makes it effectively obsolete (along with FOREACH
) with range-based for
loops. But since there are different levels of conformance with C++11, there are some environments where you have lambda but not range-based for
.
What you ought to use is up to you. FOREACH
is nice, and if you're already using Boost and/or Qt, then feel free. But I wouldn't suddenly start using these just for FOREACH
. Personally, I wouldn't use std::for_each
unless you're also using lambdas or something, due to code locality issues. Just use a for
loop.