One of the Nice Things

July 12, 2012 General News 0 Comments

About this new, fancy c++ standard is that it is now effortless to implement real "foreach" loops for iterable containers, thanks to the auto keyword and type inference:

#define foreach(elem, container, code)\
for (auto i = container.begin(); i != container.end(); ++i) {\
auto& elem = *i; {code;}}

Now, you just do, for example,
foreach(entity, entityList, entity->Draw());

That's pretty fun.

UPDATE:

Turns out that you can do something even cooler with VS2010. It uses a non-standard syntax, but there is an equivalent construct in the new c++, so something like this should, in theory, be supported by all C++11 compilers.

#define foreach(elem, container) for each (auto& elem in container)

Yes, it's that easy! Now, the nice thing is that the code body is no longer part of the macro expansion, so debugging is easier, and everything looks cleaner thanks to braces.

foreach(entity, entityList) {
entity->Update();
entity->Draw();
}