Interesting use of auto to make a foreach macro

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

std::map<int, std::string> myWords;
myWords[0] = "Hello\n";
myWords[1] = "World\n";

stl_foreach(word, myWords)
{
    printf(word->second.c_str());
}

stl_foreach_logical(word, myWords, word->second.compare("World\n") != 0)
{
    printf(word->second.c_str());
}

//prints:
Hello
World
Hello
C++11 already has a similar feature called range-based for loops.
1
2
3
4
for (auto& word : myWords)
{
	printf(word.second.c_str());
}
Oh snap!
Topic archived. No new replies allowed.