foreach () Macro

Sure, STL has foreach. But are you kidding me? It's not convenient!

Here is a (exceptionally clever) macro to implement foreach () loops over (most) STL containers. And it works! Here's how:

foreach (i, MyContainer) {

   i->do_something ();
}

YES. It is that simple. MyContainer can be most any container, a set, map, whatever. The first parameter of the macro is an iterator, which will be declared appropriately for the container (since half of what is so annoying with STL for loops is getting_the_whole::iterator defined.)

BUT THATS NOT ALL. There is also:

foreachelt (Thing, MyContainer) {

   Thing.do_something ();
}

Which actually generates a &-reference, i.e., Thing will be:

MyClass& Thing;

This is actually not quite as good as foreach(), because "Thing" ends up getting scoped outside the foreachelt() loop. This means if you do:

foreachelt (Thing, MyContainer1) {}
foreachelt (Thing, MyContainer2) {}

You will get an error (this isn't the case with foreach, though).

So it might be better to use foreach, most of the time; but for me, I very often store ref<>'s to stuff inside my containers, or you might store pointers, and so it's cleaner to use foreachelt to avoid double-dereferencing.

Voila, this one is neato skeeto. I think boost has a pretty cool foreach, too, you should look at it. Maybe it's the same, but I think probably it's not quite as easy as this one. I admit I haven't gotten into boost yet (I keep forgetting to).

AttachmentSize
foreach.h862 bytes