tags:

views:

1347

answers:

5

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.)

+3  A: 

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

anon
+3  A: 

Take a look at:

dirkgently
+4  A: 

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
I believe that BOOST_FOREACH( (pair<int,int> A), mapB) should work. Did not check though.
David Rodríguez - dribeas
Won't work, and I spent half a day trying to figure it our, until it suddenly strict me it was a macro. Macro's don't understand templates and they think the comma is just another argument to replace
Robert Gould
+2  A: 

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.

bb
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
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
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.
bb
That's the problem it's just "some", and that some is the low hanging fruit :/
Robert Gould
+2  A: 

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