C++ Gets For-Each

One of the new language features that has been added to C++0x is the for-each syntax. Anything which defines a range can be iterated over by the new syntax, including arrays, anything you can call begin and end on, or initializer lists. The syntax uses the colon operator within a for loop, like this:

int sum( const std::vector< int >& v )
{
	int val = 0;
	for (int i : v) {
		val += i;	
	}
	return val;
}

This is equivalent to the traditional, iterator-based looping mechanism:

int sum( const std::vector< int >& v )
{
	int val = 0;
	for (std::vector< int >::const_iterator iter = v.begin(), stop = v.end(); iter != stop; ++iter) {
		int i = *iter;
		val += i;	
	}
	return val;
}

The specification is quite clear on how this works for arrays, but is a bit unorthodox on how it works for more standard iterator situations. It turns out that the compiler will attempt to call begin and end functions with argument dependent lookups, and it treats std as an associated namespace. This effectively means that the compiler will search for a begin and end function on the iterable item, and if the method is not found, it will attempt to find a global function named begin or end (searching within the std namespace as well).

Unfortunately, it looks like support for this language feature does not exist in Visual Studio 2010 SP1, or Clang 2.0 (XCode 4). However, when it arrives, it will be a welcome addition to the language.

This entry was posted in C/C++ and tagged , . Bookmark the permalink.

One Response to C++ Gets For-Each

  1. polo88hu says:

    Great post! Sometimes MSVS10 makes me crazy when I realize after a few hours that my code is c++11 compliant but MSVS10 does not implemented all those features I used.

Leave a Reply

Your email address will not be published. Required fields are marked *