I thought I'd display my fun use of the new C++11 auto keyword to create a compile time foreach. It only works for STL collections, or anything that implements the STL collection iterator methods begin(), end() that return a STL iterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Standard Template Library foreach
// element = iterator name
// collection = STL data collection variable
#define stl_foreach(element, collection) \
for(auto element = collection.begin(), __end__ = collection.end(); \
element != __end__; element++)
// Standard Template Library Logical foreach
// element = iterator name
// collection = STL data collection variable
// additonal_logic = Additional logic injected into for loop
#define stl_foreach_logical(element, collection, additonal_logic) \
for(auto element = collection.begin(), __end__ = collection.end(); \
element != __end__ && (additonal_logic); element++)
This way you can create a foreach that will use your defined element name like so: