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.)
-
Take a look at the source of the BOOST_FOREACH macro (in foreach.hpp) - it's not what I would call "lean and mean" :-)
-
Take a look at:
- The Conditional Love article for an understanding of the rationale
- The Pitfalls section of documentation
- The Portability section just in case you are developing cross-platform products
- The bugs page for BOOST_FOREACH
-
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.David RodrÃguez - dribeas : I believe that BOOST_FOREACH( (pairA), mapB) should work. Did not check though. Robert Gould : 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 -
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.
Ferruccio : 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.Robert Gould : 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.bb : 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.Robert Gould : That's the problem it's just "some", and that some is the low hanging fruit :/ -
I profiled
BOOST_FOREACHversus a hand-coded loop.BOOST_FOREACHwas 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 toBOOST_FOREACHis negligible.
0 comments:
Post a Comment