Range-based for statements: from begin() to end()

One of the new features which makes C++ code much more readable, is the range-based for statements. They can be found in the standard at section [stmt.ranged]. The standard outlines 3 ways to use this new feature. As a braced initializer list, an array, or a class. It’s easy to imagine using a list, array, or other container to iterate over. But what if you want to define a new class, and use it in a range loop? What is the interface your class needs to expose?

Let’s start with braced-init-list. Pretty simple stuff and comes in handy sometimes:

for( auto& chipmunks : 
   { “Alvin”, “Simon”, “Theodore” } )
{
  // Do what chipmunks do. 
}

The array is similar to the above example. The only caveats are the list size must be known, and that the array can’t be composed of incomplete types.

Let’s move on to the interesting part, the iterations over a class. The necessary interface is as simple as a begin() and end(), either exposed as a member function, or as a free function. NOTE: Slightly more than that. The return type of the begin() and end() need to act as a pointer or an iterator.

Continue readingRange-based for statements: from begin() to end()