22

This one is for Boost experts. Are there any gotchas or details that the programmer needs to be aware of before he goes in and replaces all his old C/C++ style loops with the lean-and-mean-looking BOOST_FOREACH?

(This question is partly derived from here.)

Community
  • 1
  • 1
Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292

5 Answers5

10

Take a look at:

dirkgently
  • 108,024
  • 16
  • 131
  • 187
  • 1
    Is point 1 an issue for BOOST_FOREACH? As I understood it BOOST_FOREACH, evaluated each parameter once and only once. No? "It evaluates its arguments exactly once, leading to no nasty surprises" --docs – Catskul Jun 16 '11 at 17:47
9

BOOST_FOREACH - macro, I don't like macroses and prefer to use STL algorithms + lambda + bind.

Also C++0x will contain for-loop similar on BOOST_FOREACH:

int my_array[5] = {1, 2, 3, 4, 5};
for(int &x : my_array)
{
  x *= 2;
}

it is one additional reason for don't use partialy dead BOOST_FOREACH.

bayda
  • 13,365
  • 8
  • 39
  • 48
  • 2
    Actually, this is the reason I started using BOOST_FOREACH. The syntax is similar enough so that once the C++0x construct is available, you can update your code with a simple regex search-and-replace operation. – Ferruccio Apr 04 '09 at 11:01
  • 1
    I'm skeptic, very skeptic. tr1 is still not available everywhere and that was a long time ago. C++09 will be fully usable by 2020 at this rate, if C++ doesn't die from bloat. – Robert Gould Apr 04 '09 at 12:42
  • Yes, some peoples don't use/like STL for this time and will not use new C++0x features to 2020. But facts says next: VC and GCC compillers already supports some C++0x features. – bayda Apr 04 '09 at 13:03
  • That's the problem it's just "some", and that some is the low hanging fruit :/ – Robert Gould Apr 04 '09 at 13:40
8

As it's just a macro, you can't use commas in typenames, so
BOOST_FOREACH(pair<int,int> A, mapB){}
won't work.
For other disadvantages I'd consult the BOOST_FOREACH() documentation.

tstenner
  • 10,080
  • 10
  • 57
  • 92
7

I profiled BOOST_FOREACH versus a hand-coded loop. BOOST_FOREACH was about 30% slower in a simple loop that incremented the elements of a vector of size 100,000. So, if you are coding a small loop, it is not going to be as fast. Once your loop does major processing, Amdahl's Law kicks in and the loss due to BOOST_FOREACH is negligible.

rlbond
  • 65,341
  • 56
  • 178
  • 228
4

Take a look at the source of the BOOST_FOREACH macro (in foreach.hpp) - it's not what I would call "lean and mean" :-)