Using Token Sequences to Iterate Ranges -- Barry Revzin
There was a StackOverflow question recently that led me to want to write a new post about Ranges. Specifically, I wanted to write about some situations in which Ranges do more work than it seems like they should have to. And then what we can do to avoid doing that extra work.
Using Token Sequences to Iterate Ranges
by Barry Revzin
From the article:
The Problem
For the purposes of this post, I’m just going to talk about the very simple problem of:
for (auto elem : r) { use(elem); }
In the C++ iterator model, this desugars into something like:
auto __it = r.begin(); auto __end = r.end(); while (__it != __end) { use(*__it); ++__it; }
I used a
while
loop here deliberately, because it’s a simpler construct and it lets me write the advance step last.Now, if you want to customize the behavior of a range, those are your entry points right there. You can change what the initialization phase does (
begin()
andend()
), you can change the check against completeness (__it != __end
), you can change the read operation (*__it
), and you can change the advance operation (++__it
). That’s it. You can’t change the structure of the loop itself.That alone is enough to offer a pretty large wealth of functionality. It’s a very powerful abstraction.