I have a 'foreach' macro I use frequently in C++ that works for most STL containers:
#define foreach(var, container) \
for(typeof((container).begin()) var = (container).begin(); \
var != (container).end(); \
++var)
(Note that 'typeof' is a gcc extension.) It is used like this:
std::vector< Blorgus > blorgi = ...;
foreach(blorgus, blorgi) {
blorgus->draw();
}
I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing
foreach(pair, mymap) {
pair->second->foo();
}
I would write
foreach_value(v, mymap) {
v.foo();
}
I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.