34.4 Ranges
We've seen that there are two issues in the enumeration of ranges and the use of functors. First, we have a desire to avoid the general, though not universal, repeated stipulation of the begin() and end() methods for sequence types. Second, we have a need to avoid writing overly specific "writeonce, use nowhere else" functors.
In a discussion with my friend John Torjo,^{7} we discovered that we've had similar disenchantments with these issues, and wanted a better solution. We came up with the Range concept. Naturally, he and I see the issue slightly differently;^{8} the concept definition and component implementations presented here primarily reflect my view.
34.4.1 The Range Concept
The range concept is quite simple.
NOTE
Definition: A Range represents a bounded collection of elements, which may be accessed in an incremental fashion. It encapsulates a logical range—that is, a beginning and end point, along with rules for how to walk through it (move from the beginning to the end point)—and embodies a single entity with which client code may access the values contained within the range.
Sounds almost too simple to be meaningful, doesn't it? Well, the salient part of the definition is that it's a single entity. The canonical form of use is:
for(R r = . . .; r; ++r) { f(*r); }
or, if you don't go for all that operator overloading:
for(R r = . . .; r.is_open(); r.advance()) { f(r.current()); }
There's noticeable brevity of form, which is part the raison d'être of ranges. A range has the characteristics shown in Table 34.2.
Table 34.2 Characteristics of a notional range.
Name 
Expressions 
Semantics 
Precondition 
Postcondition 
Dereference 
*r or r.current() 
Returns the value of represented at the current position 
r has not reached its end condition 
r is unchanged 
Advance 
++r or r.advance() 
Advances r's current position 
r has not reached its end condition 
r is dereference able or has reached its end condition 
State 
r or r.is_open() 
Evaluates to true if r has reached its end condition, false otherwise 

r is unchanged 
Let's look at a couple of ranges in action:
// A range over a sequence glob_sequence gs("/usr/include/", "impcpp*"); for(sequence_range<glob_sequence> r(gs); r; ++r) { puts(*r); // Print the matched file entry to stdout } // A "notional range" for(integral_range<int> r(10, 20, 2); r; ++r) { cout << *r << endl; // Print int value at current point }
There's no way any pointer can fit the range syntax^{9} so we don't have to worry about catering for any fundamental types; this provides us with a lot of extra flexibility in the implementation. In other words, we can rely on all range instances being of class types, and therefore we can rely on the presence or absence of class type characteristics in order to specialize behavior for the algorithms that operate on ranges (see section 34.4.4).
The way this works is similar to the implementation of algorithms that manipulate Iterators [Aust1999], only simpler. My implementation of ranges simply relies on the specific range types deriving from the appropriate range type tag structure:
struct simple_range_tag {}; struct iterable_range_tag : public simple_range_tag {};
We'll see how these are used in the next sections.
34.4.2 Notional Range
Sometimes you don't have a concrete range, that is, one defined by two iterators; rather you have a notional range. It might be the odd numbers between 1 and 99. In this simple case you know that the number of odd numbers is 49 (1–97 inclusive), and so what you might do in classic STL is as shown in Listing 34.8:
Listing 34.8
struct next_odd_number { next_odd_number(int first) : m_current(first  2) {} int operator ()() { return ++++m_current; // Nasty, but it fits on one line ;/ } private: int m_current; }; std::vector<int> ints(49); std::generate(ints.begin(), ints.end(), next_odd_number(1));
Books on STL tend to show such things as perfectly reasonable examples of STL best practice. That may indeed be the case, but to me it's a whole lot of pain. First, we have the creation of a functor that will probably not be used elsewhere.
Second, and more significantly, the technique works by treating the functor as a passive producer whose actions are directed by the standard library algorithm generate(), whose bounds are, in turn, defined by the vector. This is very important, because it means that we need to know the number of results that will be created beforehand, in order to create spaces for them in the vector. Hence, we need a deep appreciation of how the producer—the functor—works. In this simple case, that is relatively straightforward—although I must confess I did get it wrong when preparing the test program! But imagine if we were computing the members of the Fibonacci series up to a usersupplied maximum value. It would be impossible to anticipate the number of steps in such a range other than by enumerating it to completion, which would be a drag, not to mention inefficient.
What we want in such cases is for the producer to drive the process, in accordance with the criteria stipulated by the code's author. Time to crank out my favorite example range, the integral_range template, whose simplified definition is shown in Listing 34.9:
Listing 34.9
template <typename T> class integral_range : public simple_range_tag { public: typedef simple_range_tag range_tag_type; typedef T value_type; // Construction public: integral_range( value_type first, value_type last , value_type increment = +1) ~integral_range() { // Ensure that the parameterising type is integral STATIC_ASSERT(0 != is_integral_type<T>::value); } // Enumeration public: operator "safe bool"() const; // See Chapter 24 value_type operator *() const; class_type &operator ++(); // Members . . . };
The integral_range performs enumeration over its logical range via member variables of the given integral type, T.
We can now rewrite the instantiation of the vector with odd numbers as follows:
std::vector<int> ints; ints.reserve(49); // No problem if this is wrong. r_copy(integral_range<int>(1, 99, 2), std::back_inserter(ints));
Note that the call to reserve() is an optimization and can be omitted without causing any change to the correctness of the code. r_copy() is a range algorithm (see section 34.4.3) that has the same semantics as the standard library algorithm copy() [Muss2001]. Now the producer, the instance of integral_range<int>, drives the process, which is as it should be. We could easily substitute a Fibonacci_range here, and the code would work correctly and efficiently, which cannot be said for the STL version.
34.4.3 Iterable Range
The Iterable range is an extension of the Notional range, with the additional provision of begin(), end() and range() methods, allowing it to be fully compatible with standard STL algorithms and usage (see section 34.4.4).
Iterable ranges usually maintain internal iterators reflecting the current and pasttheend condition positions, and return these via the begin() and end() methods. The range() method is provided to allow a given range to be cloned in its current enumeration state, although this is subject to the restrictions on copying iterators if the range's underlying iterators are of the Input or Output Iterator concepts [Aust1999, Muss2001]: only the Forward and "higher" models [Aust1999, Muss2001] support the ability to pass through a given range more than once.
It is possible to write iterable range classes, but the common idiom is to use an adaptor. In my implementation of the Range concept, I have two adaptors, the sequence_range and iterator_range template classes. Obviously the sequence_range adapts STL Sequences, and the iterator_range adapts STL Iterators.
Given a sequence type, we can adapt it to a range by passing the sequence instance to the constructor of an appropriate instantiation of sequence_range, as in:
std::deque<std::string> d = . . . ;
sequence_range< std::deque<std::string> > r(d); for(; r; ++r) { . . . // Use *r }
Similarly, an iterator_range is constructed from a pair of iterators, as in:
vector<int> v = . . . ; for(iterator_range<vector<int>::iterator> r(v.begin(), v.end()); r; ++r) { . . . // Use *r }
Iterable ranges at first glance appear to be nothing more than a syntactic convenience for reducing the clutter of unwanted variables when processing iterator ranges in unrolled loops. I must confess that this in itself represents a big attraction to draw for me, but the concept offers much more as we'll see in the next couple of sections.
34.4.4 Range Algorithms and Tags
All the examples so far have shown ranges used in unrolled loops. Ranges may also be used with algorithms. That's where the separation of Notional and Iterable range concepts comes in.
Consider the standard library algorithm distance().
template <typename I> size_t distance(I first, I last);
This algorithm returns the number of elements represented by the range [first, last). For all iterator types other than Random Access [Aust1999, Muss2001], the number is calculated by iterating first until it equals last. But the template is implemented to simply and efficiently calculate (last – first) for random access iterators. We certainly don't want to lose such efficiency gains when using algorithms with ranges.
The answer is very simple: we implement the range algorithms in terms of the standard library algorithms where possible. The range algorithm r_distance() is defined as shown in Listing 34.10:
Listing 34.10
template <typename R> ptrdiff_t r_distance_1(R r, iterable_range_tag const &) { return std::distance(r.begin(), r.end()); } template <typename R> ptrdiff_t r_distance_1(R r, simple_range_tag const &) { ptrdiff_t d = 0; for(; r; ++r, ++d) {} return d; } template <typename R> inline ptrdiff_t r_distance(R r) { return r_distance_1(r, r); }
r_distance() is implemented in terms of r_distance_1(),^{10} which has two definitions: one for the iterable ranges that defers to a standard library algorithm, and one for notional ranges that carries out the enumeration manually. The two overloads of r_distance_1() are distinguished by their second parameter, which discriminate on whether the ranges as simple or iterable.
We use run time polymorphism (inheritance) to select the compiletime polymorphism (template type resolution), so we need to pass the range to r_distance_1() in two parameters, to preserve the actual type in the first parameter while at the same type discriminating the overload in the second. Since compilers can make mincemeat of such simple things, there're no concerns regarding inefficiency, and the mechanism ably suffices. We saw in section 34.4.2 that the integral_range template inherited from simple_range_tag. Iterable ranges inherit from iterable_range_tag. Hence the implementations of all range algorithms unambiguously select the most suitable implementation.
We can now come back and address the algorithm name problem (see section 34.2.2). Since we're clearly distinguishing between iteratorpair ranges and instances of a range class, we're never going to need the same name to facilitate generalized programming because the former ranges come as two parameters and the latter as one. Therefore, we can avoid all the namespace tribulations and just use algorithms with an r_ prefix.
34.4.5 Filters
Another powerful aspect of the Range concept abstraction is that of filters. This aspect of ranges is only just developing, but is already promising great benefits. I'll illustrate with a simple filter divisible, which we'll apply to our integral_range.
Listing 34.11
template <typename R> struct divisible : public R::range_tag_type { public: typedef R filtered_range_type; typedef typename R::value_type value_type; public: divisible(filtered_range_type r, value_type div) : m_r(r) , m_div(div) { assert(div > 0); for(; m_r && 0 != (*m_r % m_div); ++m_r) {} } public: operator "safe bool"() const; // See Chapter 24 { . . . // implemented in terms of m_r's op safe bool } value_type operator *() const { return *m_r; } class_type &operator ++() { for(; m_r && 0 != (*++m_r % m_div); ) {} return *this; } private: filtered_range_type m_r; value_type m_div; };
When combined with integral_range, we can filter out all the odd numbers in a given range to only those that are wholly divisible by three, as in:
std::vector<int> ints; integral_range<int> ir(1, 99, 2); r_copy( divisible<integral_range<int> >(ir, 3) , std::back_inserter(ints));
Naturally range filters can be a lot more sophisticated than this in the real world.
34.4.6 Hypocrisy?
As someone who is against the abuse of operator overloading,^{11} I am certainly open to accusations of hypocrisy when it comes to the operators that ranges support. Clearly it can be argued, if one wished to be terribly uncharitable, that the unrealistic combination of operators provided by ranges is an abuse.
I can't really defend the concept in any purist sense, so I can fall back on the Imperfect Practitioner's Philosophy, and state that the fact that it works so well, and so simply, is worth the pricked conscience.
If you like the range concept, but don't want to go for the operator overloading, it is a simple matter to replace some or all of the operators with methods. The semantics and efficiency will be the same; only the syntax will be slightly heavier.
for(R r = . . .; r.is_open(); r.advance()) { . . . = r.current(); }