Category: ranges

  • Standard Ranges

    As you may have heard by now, Ranges got merged and will be part of C++20. This is huge news and represents probably the biggest shift the Standard Library has seen since it was first standardized way back in 1998.

    This has been a long time coming. Personally, I’ve been working toward this since at least November 2013, when I opined, “In my opinion, it’s time for a range library for the modern world,” in a blog post on input ranges. Since then, I’ve been busy building that modern range library and nailing down its specification with the help of some very talented people.

    Future blog posts will discuss how we got here and the gritty details of how the old stuff and the new stuff play together (we’re C++ programmers, we love gritty details), but this post is strictly about the what.

    What is coming in C++20?

    All of the Ranges TS — and then some — will ship as part of C++20. Here’s a handy table of all the major features that will be shipping as part of the next standard:

    Feature Example
    Fundamental concepts std::Copyable<T>
    Iterator and range concepts std::InputIterator<I>
    New convenience iterator traits std::iter_value_t<I>
    Safer range access functions std::ranges::begin(rng)
    Proxy iterator support std::iter_value_t<I> tmp =
        std::ranges::iter_move(i);
    Contiguous iterator support std::ContiguousIterator<I>
    Constrained algorithms std::ranges::sort(v.begin(), v.end());
    Range algorithms std::ranges::sort(v);
    Constrained function objects std::ranges::less
    Generalized callables std::ranges::for_each(v, &T::frobnicate);
    Projections std::ranges::sort(employees, less{},
        &Employee::id);
    Range utilities struct my_view : std::view_interface<my_view> {
    Range generators auto indices = std::view::iota(0u, v.size());
    Range adaptors for (auto x : v | std::view::filter(pred)) {

    Below, I say a few words about each. But first I wanted to revisit an old coding challenge and recast its solution in terms of standard C++20.

    Pythagorian Triples, Revisited

    Some years ago now, I wrote a blog post about how to use ranges to generate an infinite list of Pythagorean triples: 3-tuples of integers where the sum of the squares of the first two equals the square of the third.

    Below is the complete solution as it will look in standard C++20. I take the solution apart after the break.

    // A sample standard C++20 program that prints
    // the first N Pythagorean triples.
    #include <iostream>
    #include <optional>
    #include <ranges>   // New header!
    
    using namespace std;
    
    // maybe_view defines a view over zero or one
    // objects.
    template<Semiregular T>
    struct maybe_view : view_interface<maybe_view<T>> {
      maybe_view() = default;
      maybe_view(T t) : data_(std::move(t)) {
      }
      T const *begin() const noexcept {
        return data_ ? &*data_ : nullptr;
      }
      T const *end() const noexcept {
        return data_ ? &*data_ + 1 : nullptr;
      }
    private:
      optional<T> data_{};
    };
    
    // "for_each" creates a new view by applying a
    // transformation to each element in an input
    // range, and flattening the resulting range of
    // ranges.
    // (This uses one syntax for constrained lambdas
    // in C++20.)
    inline constexpr auto for_each =
      []<Range R,
         Iterator I = iterator_t<R>,
         IndirectUnaryInvocable<I> Fun>(R&& r, Fun fun)
            requires Range<indirect_result_t<Fun, I>> {
          return std::forward<R>(r)
            | view::transform(std::move(fun))
            | view::join;
      };
    
    // "yield_if" takes a bool and a value and
    // returns a view of zero or one elements.
    inline constexpr auto yield_if =
      []<Semiregular T>(bool b, T x) {
        return b ? maybe_view{std::move(x)}
                 : maybe_view<T>{};
      };
    
    int main() {
      // Define an infinite range of all the
      // Pythagorean triples:
      using view::iota;
      auto triples =
        for_each(iota(1), [](int z) {
          return for_each(iota(1, z+1), [=](int x) {
            return for_each(iota(x, z+1), [=](int y) {
              return yield_if(x*x + y*y == z*z,
                make_tuple(x, y, z));
            });
          });
        });
    
        // Display the first 10 triples
        for(auto triple : triples | view::take(10)) {
          cout << '('
               << get<0>(triple) << ','
               << get<1>(triple) << ','
               << get<2>(triple) << ')' << '\n';
      }
    }
    

    The above program prints the following:

    (3,4,5)
    (6,8,10)
    (5,12,13)
    (9,12,15)
    (8,15,17)
    (12,16,20)
    (7,24,25)
    (15,20,25)
    (10,24,26)
    (20,21,29)
    

    This program is (lazily) generating an infinite list of Pythagorean triples, taking the first 10, and printing them out. Below is a quick rundown on how it works. Along the way, I’ll point out the parts of that solution that will be standard starting in C++20.

    main()

    First, let’s look at main, which creates the infinite list of triples and prints out the first 10. It makes repeated use of for_each to define the infinite list. A use like this:

    auto x = for_each( some-range, [](auto elem) {
      return some-view;
    } );
    

    means: For every element in some-range, call the lambda. Lazily collect all the views thus generated and flatten them into a new view. If the lambda were to return view::single(elem), for instance — which returns a view of exactly one element — then the above is a no-op: first carve some-range into N subranges of 1-element each, then flatten them all back into a single range.

    Armed with that knowledge, we can make sense of the triply-nested invocations of for_each:

    for_each(iota(1), [](int z) {
      return for_each(iota(1, z+1), [=](int x) {
        return for_each(iota(x, z+1), [=](int y) {
    

    This code is generating every combination of integers x, y, and z in some order (selecting the bounds so that x and y are never larger than z, because those can’t be Pythagorean triples). At each level we create structure: we start with a single range (iota(1), described below), and then get a range of ranges where each inner range corresponds to all the combinations that share a value for z. Those inner ranges are themselves further decomposed into subranges, each of which represents all the combinations that share a value of x. And so on.

    The innermost lambda has x, y, and z and can decide whether to emit the triple or not:

    return yield_if(x*x + y*y == z*z,
        make_tuple(x, y, z));
    

    yield_if takes a Boolean (have we found a Pythagorean triple?) and the triple, and either emits an empty range or a 1-element range containing the triple. That set of ranges then gets flattened, flattened, and flattened again into the infinite list of the Pythagorean triples.

    We then pipe that infinite list to view::take(10), which truncates the infinite list to the first 10 elements. Then we iterate over those elements with an ordinary range-based for loop and print out the results. Phwew!

    Now that we have a high-level understanding of what this program is doing, we can take a closer look at the individual components.

    view::iota

    This is a very simple view. It takes either one or two objects of Incrementable type. It builds a range out of them, using the second argument as the upper bound of a half-closed (i.e., exclusive) range, taking the upper bound to be an unreachable sentinel if none is specified (i.e., the range is infinite). Here we use it to build a range of integers, but any incrementable types will do, including iterators.

    The name “iota” comes from the std::iota numeric algorithm, which itself has an interesting naming history.

    for_each

    The range-v3 library comes with view::for_each and yield_if, but those haven’t been proposed yet. But view::for_each is a trivial composition of view::transform and view::join which will be part of C++20, so we can implement it as follows:

    inline constexpr auto for_each =
      []<Range R,
         Iterator I = iterator_t<R>,
         IndirectUnaryInvocable<I> Fun>(R&& r, Fun fun)
           requires Range<indirect_result_t<Fun, I>> {
         return std::forward<R>(r)
           | view::transform(std::move(fun))
           | view::join;
      };
    

    This declares an object for_each that is a C++20 constrained generic lambda with explicitly specified template parameters. “Range” and “IndirectUnaryInvocable” are standard concepts in C++20 that live in namespace std. They constrain the arguments r and fun of the lambda to be a range (duh) and a function that is callable with the values of the range. We then further constrain the lambda with a trailing requires clause, ensuring that the function’s return type must be a Range as well. indirect_result_t will also be standard in C++20. It answers the question: if I call this function with the result of dereferencing this iterator, what type do I get back?

    The lambda first lazily transforms the range r by piping it to view::transform, moving fun in. view:: is a namespace within std:: in which all the new lazy range adaptors live. Since fun returns a Range (we required that!), the result of the transformation is a range of ranges. We then pipe that to view::join to flatten the ranges into one big range.

    The actual code, lines 6-8, kind of gets lost in the sea of constraints, which are not strictly necessary to use the library; I’m being a bit pedantic for didactic purposes here, so please don’t let that trip you up.

    I also could have very easily written for_each as a vanilla function template instead of making it an object initialized with a constrained generic lambda. I opted for an object in large part because I wanted to demonstrate how to use concepts with lambdas in C++20. Function objects have other nice properties, besides.

    yield_if

    yield_if is simpler conceptually, but it requires a little legwork on our part. It is a function that takes a Boolean and an object, and it returns either an empty range (if the Boolean is false), or a range of length one containing the object. For that, we need to write our own view type, called maybe_view, since there isn’t one in C++20. (Not yet, at least. There is a proposal.)

    Writing views is made a little simpler with the help of std::view_interface, which generates some of the boilerplate from begin() and end() functions that you provide. view_interface provides some handy members like .size(), .operator[], .front(), and .back().

    maybe_view is reproduced below. Notice how it is trivially implemented in terms of std::optional and std::view_interface.

    template<Semiregular T>
    struct maybe_view : view_interface<maybe_view<T>> {
      maybe_view() = default;
      maybe_view(T t) : data_(std::move(t)) {
      }
      T const *begin() const noexcept {
        return data_ ? &*data_ : nullptr;
      }
      T const *end() const noexcept {
        return data_ ? &*data_ + 1 : nullptr;
      }
    private:
      optional<T> data_{};
    };
    

    Once we have maybe_view, the implementation of yield_if is also trivial. It returns either an empty maybe_view, or one containing a single element, depending on the Boolean argument.

    inline constexpr auto yield_if =
      []<Semiregular T>(bool b, T x) {
        return b ? maybe_view{std::move(x)}
                 : maybe_view<T>{};
      };
    

    Note: maybe_view owns its elements. It is generally a violation of the View concept’s semantic requirements for a view to own its elements because it gives the type’s copy and move operations O(N) behavior. However, in this case — where N is either 0 or 1 — we just squeak by.

    And that’s it. This program demonstrates how to use view::iota, view::transform, view::join, view_interface, and some standard concepts to implement a very useful bit of library functionality, and then uses it to construct an infinite list with some interesting properties. If you have used list comprehensions in Python or Haskell, this should feel pretty natural.

    But these features are just a tiny slice of the range support in C++20. Below, I go through each row of the table at the top of the post, and give an example of each.

    Fundamental Concepts

    The C++20 Standard Library is getting a host of generally useful concept definitions that users can use in their own code to constrain their templates and to define higher-level concepts that are meaningful for them. These all live in the new <concepts> header, and they include things like Same<A, B>, ConvertibleTo<From, To>, Constructible<T, Args...>, and Regular<T>.

    Say for instance that you have a thread pool class with an enqueue member function that takes something that is callable with no arguments. Today, you would write it like this:

    struct ThreadPool {
      template <class Fun>
      void enqueue( Fun fun );
    };
    

    Users reading this code might wonder: what are the requirements on the type Fun? We can enforce the requirement in code using C++20’s std::Invocable concept, along with the recently-added support for abreviated function syntax:

    #include <concepts>
    
    struct ThreadPool {
      void enqueue( std::Invocable auto fun );
    };
    

    This states that fun has to be invocable with no arguments. We didn’t even have to type template <class ...>! (std::Invocable<std::error_code &> auto fun would declare a function that must be callable with a reference to a std::error_code, to take another example.)

    Iterator and Range Concepts

    A large part of the Standard Library concerns itself with containers, iterators, and algorithms, so it makes sense that the conceptual vocabulary would be especially rich in this area. Look for useful concept definitions like Sentinel<S, I>, InputIterator<I>, and RandomAccessIterator<I> in the <iterator> header, in addition to useful compositions like IndirectRelation<R, I1, I2> which test that R imposes a relation on the result of dereferencing iterators I1 and I2.

    Say for example that you have a custom container type in your codebase called SmallVector that, like std::vector, can be initialized by passing it two iterators denoting a range. We can write this with concepts from <iterator> and <concepts> as follows:

    template <std::Semiregular T>
    struct SmallVector {
      template <std::InputIterator I>
        requires std::Same<T, std::iter_value_t<I>>
      SmallVector( I i, std::Sentinel<I> auto s ) {
        // ...push back all elements in [i,s)
      }
      // ...
    

    Likewise, this type can get a constructor that takes a range directly using concepts defined in the new <ranges> header:

      // ... as before
      template <std::InputRange R>
        requires std::Same<T, std::range_value_t<R>>
      explicit SmallVector( R && r )
        : SmallVector(std::ranges::begin(r),
                      std::ranges::end(r)) {
      }
    };
    

    Note: range_value_t<R> hasn’t been formally accepted yet. It is an alias for iter_value_t<iterator_t<R>>.

    New Convenience Iterator Traits

    In C++17, if you want to know the value type of an iterator I, you have to type typename std::iterator_traits<I>::value_type. That is a mouthful. In C++20, that is vastly shortened to std::iter_value_t<I>. Here are the newer, shorter type aliases and what they mean:

    New iterator type alias Old equivalent
    iter_difference_t<I> typename iterator_traits<I>::difference_type
    iter_value_t<I> typename iterator_traits<I>::value_type
    iter_reference_t<I> typename iterator_traits<I>::reference
    iter_rvalue_reference<I> no equivalent, see below

    There is no iter_category_t<I> to get an iterator’s tag type because tag dispatching is now passé. Now that you can dispatch on iterator concept using language support, there is no need for tags.

    Safe Range Access Functions

    What is wrong with std::begin and std::end? Surprise! they are not memory safe. Consider what this code does:

    extern std::vector<int> get_data();
    auto it = std::begin(get_data());
    int i = *it; // BOOM
    

    std::begin has two overloads for const and non-const lvalues. Trouble is, rvalues bind to const lvalue references, leading to the dangling iterator it above. If we had instead called std::ranges::begin, the code would not have compiled.

    ranges::begin has other niceties besides. It does the ADL two-step for you saving you from remembering to type using std::begin; in generic code. In other words, it dispatches to a begin() free function found by ADL, but only if it returns an Iterator. That’s an extra bit of sanity-checking that you won’t get from std::begin.

    Basically, prefer ranges::begin in all new code in C++20 and beyond. It’s more better.

    Prvalue and Proxy Iterator Support

    The C++98 iterator categories are fairly restrictive. If your iterator returns a temporary (i.e., a prvalue) from its operator*, then the strongest iterator category it could model was InputIterator. ForwardIterator required operator* to return by reference. That meant that a trivial iterator that returns monotonically increasing integers by value, for example, cannot satisfy ForwardIterator. Shame, because that’s a useful iterator! More generally, any iterator that computes values on-demand could not model ForwardIterator. That’s :’-(.

    It also means that iterators that return proxies — types that act like references — cannot be ForwardIterators. Hence, whether it was a good idea or not, std::vector<bool> is not a real container since its iterators return proxies.

    The new C++20 iterator concepts solve both of this problems with the help of std::ranges::iter_swap (a constrained version of std::iter_swap), and the new std::ranges::iter_move. Use ranges::iter_swap(i, j) to swap the values referred to by i and j. And use the following:

    iter_value_t<I> tmp = ranges::iter_move(i);
    

    … to move an element at position i out of sequence and into the temporary object tmp.

    Authors of proxy iterator types can hook these two customization points to make their iterators play nicely with the constrained algorithms in the std::ranges namespace (see below).

    The new iter_rvalue_reference_t<I> type alias mentioned above names the return type of ranges::iter_move(i).

    Contiguous Iterator Support

    In Stepanov’s STL, RandomAccessIterator is the strongest iterator category. But whether elements are contiguous in memory is a useful piece of information, and there exist algorithms that can take advantage of that information to become more efficient. Stepanov was aware of that but felt that raw pointers were the only interesting model of contiguous iterators, so he didn’t need to add a new category. He would have been appalled at the library vendors who ship std::vector implementations with wrapped debug iterators.

    TL;DR, we are now defining an extra category that subsumes (refines) RandomAccessIterator called ContiguousIterator. A type must opt-in to contiguity by defining a nested type named iterator_concept (note: not iterator_category) that is an alias for the new std::contiguous_iterator_tag tag type. Or you could specialize std::iterator_traits for your type and specify iterator_concept there.

    There is a whole blog post coming about iterator_category, iterator_concept, and how to write an iterator type that conforms both to the old iterator concepts and the new, with different strengths in each. It’s a brave new world of back-compat considerations.

    Constrained Algorithms

    Ever tried to pass a std::list‘s iterator to std::sort? Or any other combination of nonesense? When you accidentally fail to meet an algorithm’s (unstated) type requirements today, your compiler will inform you in the most obscure and voluminous way possible, spewing errors that appear to come from within the guts of your STL implementation.

    Concepts are designed to help with this. For instance, look at this code that is using the cmcstl2 reference implementation (which puts std::ranges in std::experimental::ranges for now):

    #include <list>
    #include <stl2/algorithm.hpp>
    using ranges = std::experimental::ranges;
    
    int main() {
      std::list<int> l {82,3,7,2,5,8,3,0,4,23,89};
      ranges::sort( l.begin(), l.end() );
    }
    

    Rather than an error deep in the guts of ranges::sort, the error message points right to the line in main that failed to meet the constraints of the sort template. “error: no matching call for ranges::sort(list<int>::iterator, list<int>::iterator)“, followed by a message that shows the prototype that failed to match and an explanation that the constraints within RandomAccessIterator we not satisfied. You can see the full error here.

    Much can be done to make the error more user-friendly, but it’s already a vast improvement over the status quo.

    Range Algorithms

    This one is fairly obvious. It’s been 20 years since the STL was standardized, and all I want to do is pass a vector to sort. Is that too much to ask? Nope. With C++20, you will finally be able to do this:

    std::vector< int > v =  // ...
    std::ranges::sort( v ); // Hurray!
    

    Constrained Function Objects

    Have you ever used std::less<>, the “diamond” specializations of the comparison function objects that were added in C++14? These let you compare things without having to say up front what type you’re comparing or forcing conversions. These exist in the std::ranges namespace too, but you don’t have to type <> because they are not templates. Also, they have constrained function call operators. So less, greater, less_equal, and greater_equal are all constrained with StrictTotallyOrderedWith, for instance.

    These types are particularly handy when defining APIs that accept a user-specified relation, but default the relation to operator< or operator==. For instance:

    template <class T, Relation<T, T> R = ranges::less>
    T max( T a, T b, R r = {} ) {
      return r( a, b ) ? b : a;
    }
    

    This function has the nice property that if the user specifies a relation, it will be used and the constraints guarantee that R is a Relation over type T. If the user doesn’t specify a relation, then the constraints require that T satisfies StrictTotallyOrderedWith itself. That is implicit in the fact that R defaults to ranges::less, and ranges::less::operator() is constrained with StrictTotallyOrderedWith.

    Generalized Callables

    In C++17, the Standard Library got a handy function: std::invoke. It lets you call any “Callable” thing with some arguments, where “Callable” includes ordinary function-like things in addition to pointers to members. However, the standard algorithms were not respecified to use std::invoke, which meant that code like the following failed to compile:

    struct Wizard {
      void frobnicate();
    };
    
    int main() {
      std::vector<Wizard> vw { /*...*/ };
      std::for_each( vw.begin(), vw.end(),
                     &Wizard::frobnicate ); // Nope!
    }
    

    std::for_each is expecting something callable like fun(t), not std::invoke(fun, t).

    The new algorithms in the std::ranges namespace are required to use std::invoke, so if the above code is changed to use std::ranges::for_each, it will work as written.

    Projections

    Ever wanted to sort a range of things by some property of those things? Maybe sort a vector of Employees by their ids? Or last name? Or maybe you want to seach an array of points for one where the magnitude is equal to a certain value. For those things, projections are very handy. A projection is a unary transformation function passed to an algorithm that gets applied to each element before the algorithm operates on the element.

    To take the example of sorting a vector of Employees by id, you can use a projection argument to std::ranges::sort as follows:

    struct Employee {
      int Id;
      std::string Name;
      Currency Salary;
    };
    
    int main() {
      using namespace std;
      vector<Employee> employees { /*...*/ };
      ranges::sort( employees, ranges::less{},
                    &Employee::Id );
    }
    

    The third argument to std::ranges::sort is the projection. Notice that we used a generalized callable for it, from the previous section. This sort command sorts the Employees by the Id field.

    Or for the example of searching an array of points for one where the magnitude is equal to a certain value, you would do the following:

    using namespace std;
    array< Point > points { /*...*/ };
    auto it = ranges::find( points, value, [](auto p) {
      return sqrt(p.x*p.x + p.y*p.y);
    } );
    

    Here we are using a projection to compute a property of each element and operating on the computed property.

    Once you get the hang of projections, you’ll find they have many uses.

    Range Utilities

    The part of the standard library shipping in the <ranges> header has a lot of goodies. Besides an initial set of lazy range adaptors (described below), it has some handy, general-purpose utilities.

    view_interface

    As in the Pythagorean triples example above, your custom view types can inhert from view_interface to get a host of useful member functions, like .front(), .back(), .empty(), .size(), .operator[], and even an explicit conversion to bool so that view types can be used in if statements:

    // Boolean conversion operator comes from view_interface:
    if ( auto evens = vec | view::filter(is_even) ) {
      // yup, we have some evens. Do something.
    }
    

    subrange

    std::ranges::subrange<I, S> is probably the most handy of the range utilities. It is an iterator/sentinel pair that models the View concept. You can use it to bundle together two iterators, or an iterator and a sentinel, for when you want to return a range or call an API that expects a range.

    It also has deduction guides that make it quite painless to use. Consider the following code:

    auto [b,e] = subrange{vec};
    

    This code is equivalent in effect to:

    auto b = ranges::begin(vec);
    auto e = ranges::end(vec);
    

    The expression subrange{vec} deduces the iterator and sentinel template parameters from the range vec, and since subrange is tuple-like, we can unpack the iterator/sentinel pair using structured bindings.

    ref_view

    Although not officially merged yet, C++20 will have a std::ranges::ref_view<R> which, like std::reference_wrapper is, well, a wrapper around a reference. In the case of ref_view, it is a reference to a range. It turns an lvalue container like std::vector<int>& into a View of the same elements that is cheap to copy: it simply wraps a pointer to the vector.

    Range Generators

    Now we get to the really fun stuff. The <ranges> header has a couple of ways to generate new ranges of values, including std::view::iota that we saw above. Here is how to use them, and what they mean:

    Syntax Semantics
    view::iota(i) Given the incrementable object i, generates an infinite range of values like [i,i+1,i+2,i+3,...).
    view::iota(i,j) Given the incrementable object i and some other object j that is comparable to i (but not necessarily the same type), generates a range of values like [i,i+1,i+2,i+3,...,j-1]. Note that the upper bound (j) is excluded, which makes this form usable with iterator/sentinel pairs. It can also be used to generate the indices of a range with view::iota(0u, ranges::size(rng)).
    view::single(x) Construct a one-element view of the value x; that is, [x].
    view::empty<T> A zero-element view of elements of type T.
    view::counted(it, n) Given an iterator it and a count n, constructs a finite range of n elements starting at the element denoted by it.

    Range Adaptors

    This is the really, really fun stuff. The true power of ranges lies in the ability to create pipelines that transform ranges on the fly. The range-v3 library has dozens of useful range adaptors. C++20 will only be getting a handful, but expect the set to grow over time.

    Syntax Semantics
    r | view::all Create a View over all the elements in Range r. Perhaps r is already a View. If not, turn it into one with ref_view if possible, or subrange failing that. Rvalue containers are not “viewable,” and so code like std::vector<int>{} | view::all will fail to compile.
    r | view::filter(pred) Given a viewable range r and a predicate pred, return a View that consists of all the elements e for which invoke(pred, e) returns true.
    r | view::transform(fn) Given a viewable range r and a function fn, return a View that consists of all the elements of r transformed with fn.
    r | view::reverse Given a viewable range r, return a View that iterates r‘s values in reverse order.
    r | view::take(n) Given a viewable range r, return a View containing the first n elements of r, or all the elements of r if r has fewer than n elements.
    r | view::join Given a viewable range of ranges, flatten all the ranges into a single range.
    r | view::split(r2) Given a viewable range r and a pattern range r2, return a View of Views where the inner ranges are delimited by r2. Alternativly, the delimiter can be a single value v which is treated as if it were view::single(v).
    r | view::common Given a viewable range r, return a View for which the begin and end iterators of the range have the same type. (Some ranges use a sentinel for the end position.) This range adaptor is useful primarily as a means of interfacing with older code (like the std:: algorithms) that expects begin and end to have the same type.

    These adaptors can be chained, so for instance, you can do the following:

    using namespace std;
    for ( auto && e : r | view::filter(pred)
                        | view::transform(fn) ) {
      // Iterate over filtered, transformed range
    }
    

    Of course, you can also use range adaptor pipelines as arguments to the range-based algorithms in std::ranges:

    using namespace std;
    // Insert a filtered, transformed range into
    // the back of container `v`.
    ranges::copy( r | view::filter(pred)
                    | view::transform(fn),
                  back_inserter(v) );
    

    Lazily adapting ranges is a powerful way to structure your programs. If you want a demonstration of how far this programming style can take you, see my CppCon keynote on ranges from 2015, or just skim the code of the calendar application I describe there, and note the lack of loops, branches, and overt state manipulation. ‘Nuf said.

    Future Directions

    Clearly, C++20 is getting a lot of new functionality in support of ranges. Getting here has taken a long time, mostly because nobody had ever built a fully general, industrial strength, generic library using the C++20 language support for concepts before. But now we are over that hump. All the foundational pieces are in place, and we’ve acrued a lot of knowledge in the process. Expect the feature set to expand rapidly post-C++20. There are already papers in flight.

    Things currently in the works include:

    • Constructors for the standard containers that accept ranges,
    • A take_while range adaptor that accepts a predicate and returns a view of the first N elements for which the predicate evaluates to true,
    • A drop range adaptor that returns a view after dropping the first N elements of the input range,
    • A drop_while view that drops elements from an input range that satisfy a predicate.
    • An istream_view that is parameterized on a type and that reads elements of that type from a standard istream,
    • A zip view that takes N ranges and produces a view where the elements are N-tuples of the elements of the input ranges, and
    • A zip_with view that takes N ranges and a N-ary function, and produces a view where the elements are the result of calling the function with the elements of the input ranges.

    And there’s more, lots more in range-v3 that has proven useful and will eventually be proposed by myself or some other interested range-r. Things I would especially like to see:

    • An iterator façade class template like range-v3’s basic_iterator;
    • A view façade class template like range-v3’s view_facade;
    • Range-ified versions of the numeric algorithms (e.g., accumulate, partial_sum, inner_product);
    • More range generators and adaptors, like view::chunk, view::concat, view::group_by, view::cycle, view::slice, view::stride, view::generate[_n], view::repeat[_n], a view::join that takes a delimiter, view::intersperse, view::unique, and view::cartesian_product, to name the more important ones; and
    • A “complete” set of actions to go along with the views. Actions, like the adaptors in the view:: namespace, operate on ranges and compose into pipelines, but actions act eagerly on whole containers, and they are potentially mutating. (The views are non-mutating.)

    With actions, it should be possible to do:

    v = move(v) | action::sort | action::unique;
    

    …to sort a vector and remove all duplicate elements.

    And I haven’t even mentioned asynchronous ranges yet. But that’s a whole other blog post. 🙂

    Summary

    C++20 is rapidly approaching, and now that the Ranges work has been officially merged into the working draft, I have been hearing from Standard Library vendors who are starting to think about implementing all of this. Only GCC is in a position to ship the ranges support any time soon, since it is the only compiler currently shipping with support for concepts. But clang has a concepts branch which is already usable, so there is hope for concepts — and ranges — in clang trunk sometime in the not-too-distant future. And Microsoft has publicly committed to supporting all of C++20 including concepts and ranges, and the conformance of the Microsoft compiler has been rapidly improving, recently gaining the ability to compile range-v3. So things are looking good there, too.

    It’s a stRANGE new world. Thanks for reading.

    "\e"
  • Ranges, Coroutines, and React: Early Musings on the Future of Async in C++

    Disclaimer: these are my early thoughts. None of this is battle ready. You’ve been warned.

    Hello, Coroutines!

    At the recent C++ Committee meeting in Toronto, the Coroutines TS was forwarded to ISO for publication. That roughly means that the coroutine “feature branch” is finished, and is ready to be merged into trunk (standard C++) after a suitable vetting period (no less than a year). That puts it on target for C++20. What does that mean for idiomatic modern C++?

    Lots, actually. With the resumable functions (aka, stackless coroutines) from the Coroutines TS, we can do away with callbacks, event loops, and future chaining (future.then()) in our asynchronous APIs. Instead, our APIs can return “awaitable” types. Programmers can then just use these APIs in a synchronous-looking style, spamming co_await in front of any async API call and returning an awaitable type.

    This is a bit abstract, so this blog post make it more concrete. It describes how the author wrapped the interface of libuv — a C library that provides the asynchronous I/O in Node.js — in awaitables. In libuv, all async APIs take a callback and loop on an internal event loop, invoking the callback when the operation completes. Wrapping the interfaces in awaitables makes for a much better experience without the callbacks and the inversion of control they bring.

    Below, for instance, is a function that (asynchronously) opens a file, reads from it, writes it to stdout, and closes it:

    auto start_dump_file( const std::string& str )
      -> future_t<void>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          buffer.len = result;
          fs_t req;
          (void) co_await fs_write(uv_default_loop(),
                                   &req,
                                   1 /*stdout*/,
                                   &buffer,
                                   1,
                                   -1);
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    You can see that this looks almost exactly like ordinary synchronous code, with two exceptions:

    1. Calls to asynchronous operations are preceded with co_await, and
    2. The function returns an awaitable type (future_t<void>).

    Very nice. But this code snippet does too much in my opinion. Wouldn’t it be nice to have a reusable component for asynchronously reading a file, separate from the bit about writing it to stdout? What would that even look like?

    Hello, Ranges!

    Also at the recent C++ Committee meeting in Toronto, the Ranges TS was forwarded to ISO for publication. This is the first baby step toward a complete reimagining and reimplementation of the C++ standard library in which interfaces are specified in terms of ranges in addition to iterators.

    Once we have “range” as an abstraction, we can build range adaptors and build pipelines that transform ranges of values in interesting ways. More than just a curiosity, this is a very functional style that lets you program without a lot of state manipulation. The fewer states your program can be in, the easier it is for you to reason about your code, and the fewer bugs you’ll have. (For more on that, you can see my 2015 C++Con talk about ranges; or just look at the source for a simple app that prints a formatted calendar to stdout, and note the lack of loops, conditionals, and overt state manipulation.)

    For instance, if we have a range of characters, we might want to lazily convert each character to lowercase. Using the range-v3 library, you can do the following:

    std::string hello("Hello, World!");
    using namespace ranges;
    auto lower = hello
               | view::transform([](char c){
                   return (char)std::tolower(c);});
    

    Now lower presents a view of hello where each character is run through the tolower transform on the fly.

    Although the range adaptors haven’t been standardized yet, the Committee has already put its stamp of approval on the overall direction, including adaptors and pipelines. (See N4128 for the ranges position paper.) Someday, these components will all be standard, and the C++ community can encourage their use in idiomatic modern C++.

    Ranges + Coroutines == ?

    With coroutines, ranges become even more powerful. For one thing, the co_yield keyword makes it trivial to define your own (synchronous) ranges. Already with range-v3 you can use the following code to define a range of all the integers and apply a filter to them:

    #include <iostream>
    #include <range/v3/all.hpp>
    #include <range/v3/experimental/utility/generator.hpp>
    
    using namespace ranges;
    
    // Define a range of all the unsigned shorts:
    experimental::generator<unsigned short> ushorts()
    {
      unsigned short u = 0;
      do { co_yield u; } while (++u);
    }
    
    int main()
    {
      // Filter all the even unsigned shorts:
      auto evens = ushorts()
                 | view::filter([](auto i) {
                       return (i % 2) == 0; });
    
      // Write the evens to cout:
      copy( evens, ostream_iterator<>(std::cout, "\n") );
    }
    

    Put the above code in a .cpp file, compile with a recent clang and -fcoroutines-ts -std=gnu++1z, and away you go. Congrats, you’re using coroutines and ranges together. This is a trivial example, but you get the idea.

    Asynchronous Ranges

    That great and all, but it’s not asynchronous, so who cares? If it were asynchronous, what would that look like? Moving to the first element of the range would be an awaitable operation, and then moving to every subsequent element would also be awaitable.

    In the ranges world, moving to the first element of a range R is spelled “auto it = begin(R)”, and moving to subsequent elements is spelled “++it”. So for an asynchronous range, those two operations should be awaitable. In other words, given an asynchronous range R, we should be able to do:

    // Consume a range asynchronously
    for( auto it = co_await begin(R);
         it != end(R);
         co_await ++it )
    {
      auto && e = *it;
      do_something( e );
    }
    

    In fact, the Coroutines TS anticipates this and has a asynchronous range-based for loop for just this abstraction. The above code can be rewritten:

    // Same as above:
    for co_await ( auto&& e : R )
    {
      do_something( e );
    }
    

    Now we have two different but closely related abstractions: Range and AsynchronousRange. In the first, begin returns something that models an Iterator. In the second, begin returns an Awaitable of an AsynchronousIterator. What does that buy us?

    Asynchronous Range Adaptors

    Once we have an abstraction, we can program against that abstraction. Today we have a view::transform that knows how to operate on synchronous ranges. It can be extended to also work with asynchronous ranges. So can all the other range adaptors: filter, join, chunk, group_by, interleave, transpose, etc, etc. So it will be possible to build a pipeline of operations, and apply the pipeline to a synchronous range to get a (lazy) synchronous transformation, and apply the same exact pipeline to an asynchronous range to get a non-blocking asynchronous transformation. The benefits are:

    • The same functional style can be used for synchronous and asynchronous code, reusing the same components and the same idioms.
    • Asynchronous code, when expressed with ranges and transformations, can be made largely stateless, as can be done today with synchronous range-based code. This leads to programs with fewer states and hence fewer state-related bugs.
    • Range-based code composes very well and encourages a decomposition of problems into orthogonal pieces which are easily testable in isolation. (E.g., a view::filter component can be used with any input range, synchronous or asynchronous, and can be easily tested in isolation of any particular range.)

    Another way to look at this is that synchronous ranges are an example of a pull-based interface: the user extracts elements from the range and processes them one at a time. Asynchronous ranges, on the other hand, represent more of a push-based model: things happen when data shows up, whenever that may be. This is akin to the reactive style of programming.

    By using ranges and coroutines together, we unify push and pull based idioms into a consistent, functional style of programming. And that’s going to be important, I think.

    Back to LibUV

    Earlier, we wondered about a reusable libuv component that used its asynchronous operations to read a file. Now we know what such a component could look like: an asynchronous range. Let’s start with an asynchronous range of characters. (Here I’m glossing over the fact that libuv deals with UTF-8, not ASCII. I’m also ignoring errors, which is another can of worms.)

    auto async_file( const std::string& str )
      -> async_generator<char>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          // Yield the characters one at a time.
          for ( int i = 0; i < result; ++i )
          {
            co_yield buffer.buffer[i];
          }
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    The async_file function above asynchronously reads a block of text from the file and then co_yields the individual characters one at a time. The result is an asynchronous range of characters: async_generator<char>. (For an implementation of async_generator, look in Lewis Baker’s cppcoro library.)

    Now that we have an asynchronous range of characters representing the file, we can apply transformations to it. For instance, we could convert all the characters to lowercase:

    // Create an asynchronous range of characters read
    // from a file and lower-cased:
    auto async_lower = async_file("some_input.txt")
                     | view::transform([](char c){
                         return (char)std::tolower(c);});
    

    That’s the same transformation we applied above to a std::string synchronously, but here it’s used asynchronously. Such an asynchronous range can then be passed through further transforms, asynchronously written out, or passed to an asynchronous std:: algorithm (because we’ll need those, too!)

    One More Thing

    I hear you saying, “Processing a file one character at a time like this would be too slow! I want to operate on chunks.” The above async_file function is still doing too much. It should be an asynchronous range of chunks. Let’s try again:

    auto async_file_chunk( const std::string& str )
      -> async_generator<static_buf_t<1024>&>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          // Just yield the buffer.
          buffer.len = result;
          co_yield buffer;
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    Now if I want to, I can asynchronously read a block and asynchronously write the block, as the original code was doing, but while keeping those components separate, as they should be.

    For some uses, a flattened view would be more convenient. No problem. That’s what the adaptors are for. If static_buf_t is a (synchronous) range of characters, we already have the tools we need:

    // Create an asynchronous range of characters read from a
    // chunked file and lower-cased:
    auto async_lower = async_file_chunk("some_input.txt")
                     | view::join
                     | view::transform([](char c){
                         return (char)std::tolower(c);});
    

    Notice the addition of view::join. Its job is to take a range of ranges and flatten it. Let’s see what joining an asynchronous range might look like:

    template <class AsyncRange>
    auto async_join( AsyncRange&& rng )
      -> async_generator<range_value_t<
           async_range_value_t<AsyncRange>>>
    {
      for co_await ( auto&& chunk : rng )
      {
        for ( auto&& e : chunk )
          co_yield e;
      }
    }
    

    We (asynchronously) loop over the outer range, then (synchronously) loop over the inner ranges, and co_yield each value. Pretty easy. From there, it’s just a matter of rigging up operator| to async_join to make joining work in pipelines. (A fully generic view::join will be more complicated than that since both the inner and outer ranges can be either synchronous or asynchronous, but this suffices for now.)

    Summary

    With ranges and coroutines together, we can unify the push and pull programming idioms, bringing ordinary C++ and reactive C++ closer together. The C++ Standard Library is already evolving in this direction, and I’m working to make that happen both on the Committee and internally at Facebook.

    There’s LOTS of open questions. How well does this perform at runtime? Does this scale? Is it flexible enough to handle lots of interesting use cases? How do we handle errors in the middle of an asynchronous pipeline? What about splits and joins in the async call graph? Can this handle streaming interfaces? And so on. I’ll be looking into all this, but at least for now I have a promising direction, and that’s fun.

    "\e"
  • Iterators++, Part 3

    This is the fourth and final post in a series about proxy iterators, the limitations of the existing STL iterator concept hierarchy, and what could be done about it. The first three posts describe the problems of proxy iterators, the way to swap and move their elements, and how to rigorously define what an Iterator is.

    This time around I’ll be focusing on the final problem: how to properly constrain the higher-order algorithms so that they work with proxy iterators.

    A Unique Algorithm

    In this post, I’ll be looking at one algorithm in particular and how it interacts with proxy iterators: unique_copy. Here is its prototype:

    template <class InIter, class OutIter, class Fn>
    OutIter unique_copy(InIter first, InIter last,
                        OutIter result, Fn binary_pred);
    

    This algorithm copies elements from one range to another, skipping adjacent elements that are equal, using a predicate for the comparison.

    Consider the following invocation:

    std::stringstream sin{"1 1 2 3 3 3 4 5"};
    unique_copy(
      std::istream_iterator<int>{sin},
      std::istream_iterator<int>{},
      std::ostream_iterator<int>{std::cout, " "},
      std::equal_to<int>{} );
    

    This reads a bunch of ints from sin and writes the unique ones to cout. Simple, right? This code prints:

    1 2 3 4 5
    

    Think for a minute how you would implement unique_copy. First you read an int from the stream. Then you write it out to the other stream. Then you read another int. You want to compare it to the last one. Ah! You need to save the last element locally so that you can do the comparisons. Interesting.

    When I really want to understand how some part of the STL works, I check out how the feature is implemented in ye olde SGI STL. This codebase is so old, it may have first been written on parchment and compiled by monks. But it’s the cleanest and most straightforward STL implementation I know, and I recommend reading it through. Here, modulo some edits for readability, is the relevant part of unique_copy:

    // Copyright (c) 1994
    // Hewlett-Packard Company
    // Copyright (c) 1996
    // Silicon Graphics Computer Systems, Inc.
    template <class InIter, class OutIter, class Fn,
              class _Tp>
    OutIter
    __unique_copy(InIter first, InIter last,
                  OutIter result,
                  Fn binary_pred, _Tp*) {
      _Tp value = *first;
      *result = value;
      while (++first != last)
        if (!binary_pred(value, *first)) {
          value = *first;
          *++result = value;
        }
      return ++result;
    }
    

    (The calling code ensures that first != last, which explains why this code skips that check. And the strange _Tp* argument is so that the iterator’s value type can be deduced; the monks couldn’t compile traits classes.) Note the value local variable on line 11, and especially note line 14, where it passes a value and a reference to binary_pred. Keep that in mind because it’s important!

    The Plot Thickens

    You probably know more about unique_copy now than you ever cared to. Why do I bring it up? Because it’s super problematic when used with proxy iterators. Think about what happens when you try to pass vector<bool>::iterator to the above __unique_copy function:

    std::vector<bool> vb{true, true, false, false};
    using R = std::vector<bool>::reference;
    __unique_copy(
      vb.begin(), vb.end(),
      std::ostream_iterator<bool>{std::cout, " "},
      [](R b1, R b2) { return b1 == b2; }, (bool*)0 );
    

    This should write a “true” and a “false” to cout, but it doesn’t compile. Why? The lambda is expecting to be passed two objects of vector<bool>‘s proxy reference type, but remember how __unique_copy calls the predicate:

    if (!binary_pred(value, *first)) { /*...*/
    

    That’s a bool& and a vector<bool>::reference. Ouch!

    They’re just bools, and bools are cheap to copy, so take them by value. Problem solved. Well, sure, but what if they weren’t bools? What if we proxied a sequence of things that are expensive to copy? Now the problem is harder.

    So for lack of anything better (and pretending that bools are expensive to copy, bear with me), you write the lambda like this:

    [](bool& b1, R b2) { return b1 == b2; }
    

    Yuk. Now you port this code to another STL that happens to call the predicate with reversed arguments and the code breaks again. 🙁

    My point is this: once we introduce proxy iterators into the mix, it becomes non-obvious how to define predicates for use with the algorithms. Sometimes the algorithms call the predicates with references, sometimes with values, and sometimes — like unique_copy — with a mix of both. Algorithms like sort first call the predicate one way, and then later call it another way. Vive la différence!

    A Common Fix

    This problem has a very simple solution in C++14: a generic lambda. We can write the above code simply, portably, and optimally as follows:

    std::vector<bool> vb{true, true, false, false};
    std::unique_copy(
      vb.begin(), vb.end(),
      std::ostream_iterator<bool>{std::cout, " "},
      [](auto&& b1, auto&& b2) { return b1 == b2; } );
    

    No matter what unique_copy throws at this predicate, it will accommodate it with grace and style.

    But still. Polymorphic function objects feel like a big hammer. Some designs require monomorphic functions, like std::function or virtuals, or maybe even a function pointer if you have to interface with C. My point is, it feels wrong for the STL to require the use of a polymorphic function for correctness.

    To restate the problem, we don’t know how to write a monomorphic predicate for unique_copy when our sequence is proxied because value_type& may not convert to reference, and reference may not convert to value_type&. If only there were some other type, some other reference-like type, they could both convert to…

    But there is! If you read my last post, you know about common_reference, a trait that computes a reference-like type (possibly a proxy) to which two other references can bind (or convert). In order for a proxy iterator to model the Iterator concept, I required that an iterator’s reference type and its value_type& must share a common reference. At the time, I insinuated that the only use for such a type is to satisfy the concept-checking machinery. But there’s another use for it: the common reference is the type we could use to define our monomorphic predicate.

    I can imagine a future STL providing the following trait:

    // An iterator's common reference type:
    template <InputIterator I>
    using iterator_common_reference_t =
      common_reference_t<
        typename iterator_traits<I>::value_type &
        typename iterator_traits<I>::reference>;
    

    We could use that trait to write the predicate as follows:

    using I = vector<bool>::iterator;
    using C = iterator_common_reference_t<I>;
    auto binary_pred = [](C r1, C r2) {
      return r1 == r2;
    };
    

    That’s certainly a fair bit of hoop-jumping just to define a predicate. But it’s not some new complexity that I’m introducing. unique_copy and vector<bool> have been there since 1998. I’m just trying to make them play nice.

    And these hoops almost never need to be jumped. You’ll only need to use the common reference type when all of the following are true: (a) you are dealing with a proxied sequence (or are writing generic code that could deal with proxied sequences), (b) taking the arguments by value is undesirable, and (c) using a polymorphic function is impossible or impractical for some reason. I wouldn’t think that’s very often.

    Algorithm Constraints

    So that’s how things look from the perspective of the end user. How do they look from the other side, from the perspective of the algorithm author? In particular, how should unique_copy look once we use Concepts Lite to constrain the algorithm?

    The Palo Alto TR takes a stab at it. Here is how it constrains unique_copy:

    template <InputIterator I, WeaklyIncrementable Out,
              Semiregular R>
    requires Relation<R, ValueType<I>, ValueType<I>> &&
             IndirectlyCopyable<I, Out>
    Out unique_copy(I first, I last, Out result, R comp);
    

    There’s a lot going on there, but the relevant part is Relation<R, ValueType<I>, ValueType<I>>. In other words, the type R must be an equivalence relation that accepts arguments of the range’s value type. For all the reasons we’ve discussed, that doesn’t work when dealing with a proxied range like vector<bool>.

    So what should the constraint be? Maybe it should be Relation<R, ValueType<I>, Reference<I>>? But no, unique_copy doesn’t always need to copy a value into a local. Only when neither the input nor the output iterators model ForwardIterator. So sometimes the unique_copy calls the predicate like pred(*i,*j) and sometimes like pred(value, *i). The constraint has to be general enough to accommodate that.

    Maybe it could also use the iterator’s common reference type? What if we constrained unique_copy like this:

    template <InputIterator I, WeaklyIncrementable Out,
              Semiregular R>
    requires Relation<R, CommonReferenceType<I>,
                         CommonReferenceType<I>> &&
             IndirectlyCopyable<I, Out>
    Out unique_copy(I first, I last, Out result, R comp);
    

    This constraint make a promise to callers: “I will only pass objects of type CommonReferenceType<I> to the predicate.” But that’s a lie. It’s not how unique_copy is actually implemented. We could change the implementation to fulfill this promise by casting the arguments before passing them to the predicate, but that’s ugly and potentially inefficient.

    Really, I think we have to check that the predicate is callable with all the possible combinations of values and references. That sucks, but I don’t see a better option. With some pruning, these are the checks that I think matter enough to be required:

    Relation<R, ValueType<I>, ValueType<I>> &&
    Relation<R, ValueType<I>, ReferenceType<I>> &&
    Relation<R, ReferenceType<I>, ValueType<I>> &&
    Relation<R, ReferenceType<I>, ReferenceType<I>> &&
    Relation<R, CommonReferenceType<I>, CommonReferenceType<I>>
    

    As an implementer, I don’t want to write all that, and our users don’t want to read it, so we can bundle it up nice and neat:

    IndirectRelation<R, I, I>
    

    That’s easier on the eyes and on the brain.

    Interesting Indirect Invokable Implications

    In short, I think that everywhere the algorithms take a function, predicate, or relation, we should add a constraint like IndirectFunction, IndirectPredicate, or IndirectRelation. These concepts will require that the function is callable with a cross-product of values and references, with an extra requirement that the function is also callable with arguments of the common reference type.

    This might seem very strict, but for non-proxy iterators, it adds exactly zero new requirements. And even for proxy iterators, it’s only saying in code the things that necessarily had to be true anyway. Rather than making things harder, the common reference type makes them easier: if your predicate takes arguments by the common reference type, all the checks succeed, guaranteed.

    It’s possible that the common reference type is inefficient to use. For instance, the common reference type between bool& and vector<bool>::reference is likely to be a variant type. In that case, you might not want your predicate to take arguments by the common reference. Instead, you’d want to use a generic lambda, or define a function object with the necessary overloads. The concept checking will tell you if you forgot any overloads, ensuring that your code is correct and portable.

    Summary

    That’s the theory. I implemented all this in my Range-v3 library. Now I can sort a zip range of unique_ptrs. So cool.

    Here, in short, are the changes we would need to make the STL fully support proxy iterators:

    1. The algorithms need to use iter_swap consistently whenever elements need to be swapped. iter_swap should be a documented customization point.
    2. We need an iter_move customization point so that elements can be moved out of and back into sequence. This gives iterators a new rvalue_reference associated type.
    3. We need a new common_reference trait that, like common_type, can be specialized on user-defined types.
    4. All iterators need to guarantee that their value_type and reference associated types share a common reference. Likewise for value_type/rvalue_reference, and for reference/rvalue_reference.
    5. We need IndirectFunction, IndirectPredicate, and IndirectRelation concepts as described above. The higher-order algorithms should be constrained with them.

    From the end users’ perspective, not a lot changes. All existing code works as it did before, and all iterators that are valid today continue being valid in the future. Some proxy iterators, like vector<bool>‘s, would need some small changes to model the Iterator concept, but afterward those iterators are on equal footing with all the other iterators for the first time ever. Code that deals with proxy sequences might need to use common_reference when defining predicates, or they might need to use a generic lambda instead.

    So that’s it. To the best of my knowledge, this is the first comprehensive solution to the proxy iterator problem, a problem we’ve lived with from day one, and which only promises to get worse with the introduction of range views. There’s some complexity for sure, but the complexity seems to be necessary and inherent. And honestly I don’t think it’s all that bad.

    Future Directions

    I’m unsure where this goes from here. I plan to sit on it for a bit to see if any better solutions come along. There’s been some murmuring about a possible language solution for proxy references, but there is inherent complexity to proxy iterators, and it’s not clear to me at this point how a language solution would help.

    I’m currently working on what I believe will be the first draft of a Ranges TS. That paper will not address the proxy iterator problem. I could imagine writing a future paper that proposes the changes I suggest above. Before I do that, I would probably try to start a discussion on the committee mailing lists to feel people out. If any committee members are reading this, feel free to comment below.

    Thanks for following along, and thanks for all your encouraging and thought-provoking comments. Things in the C++ world are moving fast these days. It’s tough to keep up with it all. I feel blessed that you all have invested so much time exploring these issues with me. <3

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • Iterators++, Part 2

    Disclaimer: This is a long, boring post about minutia. For serious library wonks only.

    This is the third in a series about proxy iterators, the limitations of the existing STL iterator concept hierarchy, and what could be done about it. In the first post I explained what proxy iterators are (an iterator like vector<bool>‘s that, when dereferenced, returns a proxy object rather than a real reference) and three specific difficulties they cause in today’s STL:

    1. What, if anything, can we say in general about the relationship between an iterator’s value type and its reference type?
    2. How do we constrain higher-order algorithms like for_each and find_if that take functions that operate on a sequence’s elements?
    3. How do we implement algorithms that must swap and move elements around, like sort and reverse?

    In the second post, I zoomed in on the problem (3) and showed how the existing std::iter_swap API could be pressed into service, along with a new API that I propose: std::iter_move. Together, these APIs give an iterator a channel through which to communicate to the algorithms how its elements should be swapped and moved. With the addition of the iter_move API, iterators pick up a new associated type: rvalue_reference, which can live in std::iterator_traits alongside the existing value_type and reference associated types.

    In this post, I’ll dig into the first problem: how we define in code what an iterator is.

    Values and References

    As in the first two articles, I’ll use the zip view to motivate the discussion, because it’s easy to grok and yet totally bedeviling for the STL algorithms. Recall that zip lazily adapts two sequences by making them look like one sequence of pairs, as demonstrated below:

    std::vector<int> x{1,2,3,4};
    std::vector<int> y{9,8,7,6};
    
    using namespace ranges;
    auto zipped = view::zip(x, y);
    
    assert(*zipped.begin() == std::make_pair(1,9));
    assert(&(*zipped.begin()).first == &x[0]);
    

    As the two assertions above show, dereferencing a zip iterator yields a pair, and that the pair is actually a pair of references, pointing into the underlying sequences. The zip range above has the following associated types:

    Associated type… … for the zip view
    value_type pair<int, int>
    reference pair<int &, int &>
    rvalue_reference pair<int &&, int &&>

    With Concepts coming to C++, we’re going to need to say in code what an iterator is. The Palo Alto TR, published in 2012, takes a stab at it: an InputIterator is Readable and Incrementable, where Readable is defined as follows:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            { *i } -> const ValueType<I> &;
        };
    

    This says that a Readable type has an associated ValueType. It also says that *i is a valid expression, and that the result of *i must be convertible to const ValueType<I> &. This is fine when *i returns something simple like a real reference. But when it returns a proxy reference, like the zip view does, it causes problems.

    Substituting a zip iterator into the requires clause above results in something like this:

    const pair<int,int>& x = *i;
    

    This tries to initialize x with a pair<int&, int&>. This actually works in a sense; the temporary pair<int &, int &> object is implicitly converted into a temporary pair<int, int> by copying the underlying integers, and that new pair is bound to the const & because temporaries can bind to const references.

    But copying values is not what we want or expect. If instead of ints, we had pairs of some move-only type like unique_ptr, this wouldn’t have worked at all.

    So the Readable concept needs to be tweaked to handle proxy references. What can we do?

    One simple way to make the zip iterator model the Readable concept is to simply remove the requirement that *i be convertible to const ValueType<I>&. This is unsatisfying. Surely there is something we can say about the relationship between an iterator’s reference type and its value type. I think there is, and there’s a hint in the way the Palo Alto TR defines the EqualityComparable constraint.

    Common Type Constraints

    What do you think about code like this?

    vector<string> strs{"three", "blind", "mice"};
    auto it = find(strs.begin(), strs.end(), "mice");
    

    Seems reasonable, right? This searches a range of string‘s for a char const*. This should this work, even though it’s looking for an orange in a bucket of apples. The orange is sufficiently apple-like, and because we know how to compare apples and oranges; i.e., there is an operator== that compares strings with char const*. But what does “sufficiently apple-like” mean? If we are ever to constrain the find algorithm with Concepts, we need to be able to say in code what “apple-like” means for any apple and any orange.

    The Palo Alto TR doesn’t think that the mere existence of an operator== is enough. Instead, it defines the cross-type EqualityComparable concept as follows:

    template< typename T1, typename T2 >
    concept bool EqualityComparable =
        EqualityComparable<T1> &&
        EqualityComparable<T2> &&
        Common<T1, T2> &&
        EqualityComparable< std::common_type_t<T1, T2> > &&
        requires(T1 a, T2 b) {
            { a == b } -> bool;
            { b == a } -> bool;
            { a != b } -> bool;
            { b != a } -> bool;
            /* axioms:
                using C = std::common_type_t<T1, T2>;
                a == b <=> C{a} == C{b};
                a != b <=> C{a} != C{b};
                b == a <=> C{b} == C{a};
                b != a <=> C{b} != C{a};
            */
        };
    

    In words, what this says is for two different types to be EqualityComparable, they each individually must be EqualityComparable (i.e., with themselves), they must be comparable with each other, and (the key bit) they must share a common type which is also EqualityComparable, with identical semantics.

    The question then becomes: do std::string and char const * share a common type, to which they can both be converted, and which compares with the same semantics? In this case, the answer is trivial: std::string is the common type.

    Aside: why does the Palo Alto TR place this extra CommonType requirement on the argument to find when surely that will break some code that works and is “correct” today? It’s an interesting question. The justification is mathematical and somewhat philosophical: when you compare things for equality, you are asking if they have the same value. Just because someone provides an operator== to compare, say, an Employee with a SocialSecurityNumber doesn’t make an employee a social security number, or vice versa. If we want to be able to reason mathematically about our code (and we do), we have to be able to substitute like for like. Being able to apply equational reasoning to our programs is a boon, but we have to play by its rules.

    Readable and Common

    You may be wondering what any of this have to do with the Readable concept. Let’s look again at the concept as the Palo Alto TR defines it:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            { *i } -> const ValueType<I> &;
        };
    

    To my mind, what this is trying to say is there there is some substitutability, some mathematical equivalence, between an iterator’s reference type and its value type. EqualityComparable uses Common to enforce that substitutability. What if we tried to fix Readable in a similar way?

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires Common< ValueType<I>, decltype(*i) >;
        };
    

    Here we’re saying that for Readable types, the reference type and the value type must share a common type. The common type is computed using something like std::common_type_t, which basically uses the ternary conditional operator (?:). (I say “something like” since std::common_type_t isn’t actually up to the task. See lwg2408 and lwg2465.)

    Sadly, this doesn’t quite solve the problem. If you try to do common_type_t<unique_ptr<int>, unique_ptr<int>&> you’ll see why. It doesn’t work, despite the fact that the answer seems obvious. The trouble is that common_type always strips top-level const and reference qualifiers before testing for the common type with the conditional operator. For move-only types, that causes the conditional operator to barf.

    I’ve always found it a bit odd that common_type decays its arguments before testing them. Sometimes that’s what you want, but sometimes (like here) its not. Instead, what we need is a different type trait that test for the common type, but preserves reference and cv qualifications. I call it common_reference. It’s a bit of a misnomer though, since it doesn’t always return a reference type, although it might.

    The common reference of two types is the minimally qualified type to which objects of both types can bind. common_reference will try to return a reference type if it can, but fall back to a value type if it must. Here’s some examples to give you a flavor:

    Common reference… … result
    common_reference_t<int &, int const &> int const &
    common_reference_t<int &&, int &&> int &&
    common_reference_t<int &&, int &> int const &
    common_reference_t<int &, int> int

    With a common_reference type trait, we could define a CommonReference concept and specify Readable in terms of it, as follows:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires CommonReference<
                ValueType<I> &,
                decltype(*i) && >;
        };
    

    The above concept requires that there is some common reference type to which both *i and a mutable object of the iterator’s value type can bind.

    This, I think, is sufficiently general to type check all the iterators that are valid today, as well as iterators that return proxy references (though it takes some work to see that). We can further generalize this to accommodate the iter_move API I described in my previous post:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires CommonReference<
                ValueType<I> &,
                decltype(*i) && >;          // (1)
            requires CommonReference<
                decltype(iter_move(i)) &&,
                decltype(*i) && >;          // (2)
            requires CommonReference<
                ValueType<I> const &,
                decltype(iter_move(i)) &&>; // (3)
        };
    

    OK, let’s see how this works in practice.

    Iterators and CommonReference

    First, let’s take the easy case of an iterator that returns a real reference like int&. The requirements are that its value type, reference type, and rvalue reference type satisfy the three CommonReference constraints above. (1) requires a common reference between int& and int&. (2), between int&& and int&, and (3) between int const& and int&&. These are all demonstrably true, so this iterator is Readable.

    But what about the zip iterator? Things here are much trickier.

    The three common reference constraints for the zip iterator amount to this:

    Common reference… … result
    common_reference_t<
    pair<int,int> &,
    pair<int&,int&> &&>
    ???
    common_reference_t<
    pair<int&&,int&&> &&,
    pair<int&,int&> &&>
    ???
    common_reference_t<
    pair<int,int> const &,
    pair<int&&,int&&> &&>
    ???

    Yikes. How is the common_reference trait supposed to evaluate this? The ternary conditional operator is just not up to the task.

    OK, let’s first imagine what we would like the answers to be. Taking the last one first, consider the following code:

    void foo( pair< X, Y > p );
    
    pair<int,int> const & a = /*...*/;
    pair<int &&,int &&> b {/*...*/};
    
    foo( a );
    foo( move(b) );
    

    If there are types that we can pick for X and Y that make this compile, then we can make pair<X,Y> the “common reference” for pair<int&&,int&&>&& and pair<int,int> const &. Indeed there are: X and Y should both be int const &.

    In fact, for each of the CommonReference constraints, we could make the answer pair<int const&,int const&> and be safe. So in principle, our zip iterator can model the Readable concept. W00t.

    But look again at this one:

    common_reference_t<pair<int,int> &, pair<int&,int&> &&>
    

    If this coughs up pair<int const&,int const&> then we’ve lost something in the translation: the ability to mutate the elements of the pair. In an ideal world, the answer would be pair<int&,int&> because a conversion from both pair<int,int>& and pair<int&,int&>&& would be safe and meets the “minimally qualified” spirit of the common_reference trait. But this code doesn’t compile:

    void foo( pair< int&,int& > p );
    
    pair<int,int> a;
    pair<int&,int&> b {/*...*/};
    
    foo( a );       // ERROR here
    foo( move(b) );
    

    Unfortunately, pair doesn’t provide this conversion, even though it would be safe in theory. Is that a defect? Perhaps. But it’s something we need to work with.

    Long story short, the solution I went with for range-v3 is to define my own pair-like type with the needed conversions. I call it common_pair and it inherits from std::pair so that things behave as you would expect. With common_pair and a few crafty specializations of common_reference, the Readable constraints are satisfied for the zip iterator as follows:

    Common reference… … result
    common_reference_t<
    pair<int,int> &,
    common_pair<int&,int&> &&>
    common_pair<int&,int&>
    common_reference_t<
    common_pair<int&&,int&&> &&,
    common_pair<int&,int&> &&>
    common_pair<int const&,int const&>
    common_reference_t<
    pair<int,int> const &,
    common_pair<int&&,int&&> &&>
    common_pair<int const&,int const&>

    Computing these types is not as tricky as it may appear at first. For types like pair<int,int>& and common_pair<int&,int&>&&, it goes like this:

    1. Distribute any top-level ref and cv qualifiers to the members of the pair. pair<int,int>& becomes pair<int&,int&>, and common_pair<int&,int&>&& becomes common_pair<int&,int&>.
    2. Compute the element-wise common reference, and bundle the result into a new common_pair, resulting in common_pair<int&,int&>.

    Generalizing

    Our zip iterator, with enough ugly hackery, can model our re-specified Readable concept. That’s good, but what about other proxy reference types, like vector<bool>‘s? If vector<bool>‘s reference type is bool_ref, then we would need to specialize common_reference such that the Readable constraints are satisfied. This will necessarily involve defining a type such that it can be initialized with either a bool_ref or with a bool&. That would be a decidedly weird type, but it’s not impossible. (Imagine a variant<bool&,bool_ref> if you’re having trouble visualizing it.)

    Getting vector<bool>‘s iterators to fit the mold is an ugly exercise in hackery, and actually using its common reference (the variant type) would incur a performance hit for every read and write. But the STL doesn’t actually need to use it. It just needs to exist.

    What is the point of jumping through these hoops to implement an inefficient type that in all likelihood will never actually be used? This is going to be unsatisfying for many, but the answer is for the sake of mathematical rigour. There must be some substitutability relationship between an iterator’s reference type and its value type that is enforceable. Requiring that they share a common reference is the best I’ve come up with so far. And as it turns out, this “useless” type actually does have some uses, as we’ll see in the next installment.

    Summary

    So here we are. There is a way to define the Readable concept — and hence the InputIterator concept — in a way that is general enough to permit proxy iterators while also saying something meaningful and useful about an iterator’s associated types. Actually defining a proxy iterator such that it models this concept is no small feat and requires extensive amounts of hack work. BUT IT’S POSSIBLE.

    One could even imagine defining a Universal Proxy Reference type that takes a getter and setter function and does all the hoop jumping to satisfy the Iterator concepts — one proxy reference to rule them all, if you will. That’s left as an exercise for the reader.

    If you made it this far, congratulations. You could be forgiven for feeling a little let down; this solution is far from ideal. Perhaps it’s just awful enough to spur a real discussion about how we could change the language to improve the situation.

    In the next installment, I’ll describe the final piece of the puzzle: how do we write the algorithm constraints such that they permit proxy iterators? Stay tuned.

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • Iterators++, Part 1

    In the last post, I described the so-called proxy iterator problem: the fact that iterators that return proxy references instead of real references don’t sit comfortably within the STL’s framework. Real, interesting, and useful iterators fall foul of this line, iterators like vector<bool>‘s or like the iterator of the zip view I presented. In this post, I investigate what we could do to bring proxy iterators into the fold — what it means for both the iterator concepts and for the algorithms. Since I’m a library guy, I restrict myself to talking about pure library changes.

    Recap

    As in the last post, we’ll use the zip view to motivate the discussion. Given two sequences like:

    vector<int> x{1,2,3,4};
    vector<int> y{9,8,7,6};
    

    …we can create a view by “zipping” the two into one, where each element of the view is a pair of corresponding elements from x and y:

    using namespace ranges;
    auto rng = view::zip(x, y);
    
    assert(*rng.begin() == make_pair(1,9));
    

    The type of the expression “*rng.begin()” — the range’s reference type — is pair<int&,int&>, and the range’s value type is pair<int,int>. The reference type is an example of a proxy: an object that stands in for another object, or in this case two other objects.

    Since both x and y are random access, the resulting zip view should be random access, too. But here we run foul of STL’s “real reference” requirement: for iterators other than input iterators, the expression *it must return a real reference. Why? Good question! The requirement was added sometime while the STL was being standardized. I can only guess it was because the committee didn’t know what it meant to, say, sort or reverse elements that aren’t themselves persistent in memory, and they didn’t know how to communicate to the algorithms that a certain temporary object (the proxy) is a stand-in for a persistent object. (Maybe someone who was around then can confirm or deny.)

    The real-reference requirement is quite restrictive. Not only does it mean the zip view can’t be a random access sequence, it also means that you can’t sort or reverse elements through a zip view. It’s also the reason why vector<bool> is not a real container.

    But simply dropping the real-reference requirement isn’t enough. We also need to say what it means to sort and reverse sequences that don’t yield real references. In the last post, I described three specific problems relating to constraining and implementing algorithms in the presence of proxy references.

    1. What, if anything, can we say about the relationship between an iterator’s value type and its reference type?
    2. How do we constrain higher-order algorithms like for_each and find_if that take functions that operate on a sequence’s elements?
    3. How do we implement algorithms that must swap and move elements around, like sort?

    Let’s take the last one first.

    Swapping and Moving Elements

    If somebody asked you in a job interview to implement std::reverse, you might write something like this:

    template< class BidiIter >
    void reverse( BidiIter begin, BidiIter end )
    {
        using std::swap;
        for(; begin != end && begin != --end; ++begin)
            swap(*begin, *end);
    }
    

    Congratulations, you’re hired. Now, if the interviewer asked you whether this algorithm works on the zip view I just described, what would you say? The answer, as you may have guessed, is no. There is no overload of swap that accepts pair rvalues. Even if there were, we’re on thin ice here with the zip view’s proxy reference type. The default swap implementation looks like this:

    template< class T >
    void swap( T & t, T & u )
    {
        T tmp = move(u);
        u = move(t);
        t = move(tmp);
    }
    

    Imagine what happens when T is pair<int&,int&>. The first line doesn’t move any values; tmp just aliases the values referred to by u. The next line stomps the values in u, which mutates tmp because it’s an alias. Then we copy those stomped values back to t. Rather than swapping values, this makes them both equal to t. Oops.

    If at this point you’re smugly saying to yourself that pair has its own swap overload that (almost) does the right thing, you’re very smart. Shut up. But if you’re saying that the above is not a standard-conforming reverse implementation because, unlike all the other algorithms, reverse is required to use iter_swap, then very good! That’s the clue to unraveling this whole mess.

    iter_swap

    iter_swap is a thin wrapper around swap that takes iterators instead of values and swaps the elements they refer to. It’s an exceedingly useless function, since iter_swap(a,b) is pretty much required to just call swap(*a,*b). But what if we allowed it to be a bit smarter? What if iter_swap were a full-fledged customization point that allowed proxied sequences to communicate to the algorithms how their elements should be swapped?

    Imagine the zip view’s iterators provided an iter_swap that knew how to truly swap the elements in the underlying sequences. It might look like this:

    template< class It1, class It2 >
    struct zip_iterator
    {
        It1 it1;
        It2 it2;
    
        /* ... iterator interface here... */
    
        friend void iter_swap(zip_iterator a, zip_iterator b)
        {
            using std::iter_swap;
            iter_swap(a.it1, b.it1);
            iter_swap(a.it2, b.it2);
        }
    };
    

    Now we would implement reverse like this:

    template< class BidiIter >
    void reverse( BidiIter begin, BidiIter end )
    {
        using std::iter_swap;
        for(; begin != end && begin != --end; ++begin)
            iter_swap(begin, end);
    }
    

    Voilà! Now reverse works with zip views. That was easy. All that is required is (a) to advertise iter_swap as a customization point, and (b) use iter_swap consistently throughout the standard library, not just in reverse.

    iter_move

    We haven’t fixed the problem yet. Some algorithms don’t just swap elements; they move them. For instance stable_sort might allocate a temporary buffer and move elements into it while it works. You can’t use iter_swap to move an element into raw storage. But we can use a play from the iter_swap playbook to solve this problem. Let’s make an iter_move customization point that gives iterators a way to communicate how to move values out of the sequence.

    iter_move‘s default implementation is almost trivial:

    template< class I,
        class R = typename iterator_traits< I >::reference >
    conditional_t<
        is_reference< R >::value,
        remove_reference_t< R > &&,
        R >
    iter_move( I it )
    {
        return move(*it);
    }
    

    The only tricky bit is the declaration of the return type. If *it returns a temporary, we just want to return it by value. Otherwise, we want to return it by rvalue reference. If you pass a vector<string>::iterator to iter_move, you get back a string && as you might expect.

    How does the zip view implement iter_move? It’s not hard at all:

    template< class It1, class It2 >
    struct zip_iterator
    {
        It1 it1;
        It2 it2;
    
        /* ... iterator interface here... */
    
        friend auto iter_move(zip_iterator a)
        {
            using std::iter_move;
            using RRef1 = decltype(iter_move(a.it1));
            using RRef2 = decltype(iter_move(a.it2));
            return pair<RRef1, RRef2>{
                iter_move(a.it1),
                iter_move(a.it2)
            };
        }
    };
    

    The algorithms can use iter_move as follows:

    // Move an element out of the sequence and into a temporary
    using V = typename iterator_traits< I >::value_type;
    V tmp = iter_move( it );
    // Move the value back into the sequence
    *it = move( tmp );
    

    As an aside, this suggests a more general default implementation of iter_swap:

    template< class I >
    void iter_swap( I a, I b )
    {
        using V = typename iterator_traits< I >::value_type;
        V tmp = iter_move( a );
        *a = iter_move( b );
        *b = move( tmp );
    }
    

    Now proxy sequences like zip only have to define iter_move and they gets a semantically correct iter_swap for free. It’s analogous to how the default std::swap is defined in terms of std::move. (Doing it this way doesn’t pick up user-defined overloads of swap. That’s bad. There’s a work-around, but it’s beyond the scope of this post.)

    For a zip view that has value type pair<T,U> and reference type pair<T&,U&>, the return type of iter_move is pair<T&&,U&&>. Makes perfect sense. Take another look at the default implementation of iter_swap above and satisfy yourself that it correctly swaps zipped elements, even if the underlying sequences have move-only value types.

    One final note about iter_move: the implication is that to support proxied sequences, iterators need an extra associated type: the return type of iter_move. We can call it rvalue_reference and put it in iterator_traits alongside value_type and reference.

    Alternate Design

    I find the above design clean and intuitive. But it raises an interesting question: is it OK that iter_swap(a,b) and swap(*a,*b) might mean different things? Personally I think that’s OK, but let’s imagine for a moment that it’s not. What else could we do?

    An obvious alternate design is to overload swap for proxy references to swap the objects they refer to. Let’s imagine we add the following overload to namespace std:

    template< class T, class U >
    void swap( pair< T&, U& > && a, pair< T&, U& > && b )
    {
        swap(a.first, b.first);
        swap(a.second, b.second);
    }
    

    With enough SFINAE magic we could further generalize this to support swapping pairs of proxy references, but let’s stick with this. I could live with it.

    But as before, this isn’t enough; we would also need to overload move to take a pair<T&,U&> and return a pair<T&&,U&&>. And this is where I start getting uncomfortable, because move is used everywhere and it’s currently not a customization point. How much code is out there that assumes the type of a move expression is &&? What breaks when that’s no longer true?

    Purely as a matter of library evolution, overloading move that way for pairs of references is a non-starter because it would be changing the meaning of existing code. We could avoid the problem by changing zip‘s reference type from pair<T&,U&> to magic_proxy_pair< T&, U& > and overloading swap and move on that. magic_proxy_pair would inherit from pair, so most code would be none the wiser. Totally valid design.

    Summary, For Now

    I’ve run long at the mouth, and I still have two more issues to deal with, so I’ll save them for another post. We’ve covered a lot of ground. With the design suggested above, algorithms can permute elements in proxied sequences with the help of iter_swap and iter_move, and iterators get a brand new associated type called rvalue_reference.

    Whether you prefer this design or the other depends on which you find more distasteful:

    1. iter_swap(a,b) can be semantically different than swap(*a,*b), or
    2. move is a customization point that is allowed to return some proxy rvalue reference type.

    In the next installment, I’ll describe what we can say about the relationship between an iterator’s value type and its reference type (and now its rvalue reference type), and how we can constrain higher-order algorithms like for_each and find_if.

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • To Be or Not to Be (an Iterator)

    Way back in 1999, when the ink on the first C++ standard was still damp, Herb Sutter posed a GoTW puzzler in the still extant C++ Report (RIP): When Is a Container Not a Container? In that article, Herb described the problems of the now-infamous vector<bool>. According to the standard’s own container requirements, vector<bool> is not a container.

    In a nutshell, it’s because vector<bool>‘s iterators claim to be random-access, but they’re not. Random-access iterators, when you dereference them, must return a real reference. They can only do that if the thing they point to really exists somewhere. But the bool that a vector<bool>::iterator points to does not exist anywhere. It’s actually a bit in a packed integer, and dereferencing a vector<bool>‘s iterator returns an object of some type that merely acts like a bool& without actually being a bool&.

    Herb goes so far as to say this:

    […] although a proxied collection can be an important and useful tool, by definition it must violate the standard’s container requirements and therefore can never be a conforming container.

    At the end of his article, Herb suggests that people stop using vector<bool> and use std::bitset if they want bit-packing. But that just pushes the problem around. Why shouldn’t std::bitset be a conforming container with random-access iterators? If proxied collections are so useful, why should we content ourselves with a standard library that treats them like second-class citizens?

    A Brief History of Proxy Iterators

    Herb wrote his article in 1999, so we’ve been living with this problem for a long time. Many have tried to fix it and ultimately failed for one reason or another. Mostly it’s because all the solutions have tried to be backwards compatible, shoehorning a richer iterator hierarchy into a standard that doesn’t easily allow it, or else breaking iterators themselves apart into separate objects that control traversal and element access. Each time the committee has balked, preferring instead the devil it knew.

    An interesting historical note: the original STL design didn’t have the “true reference” requirement that causes the problem. Take a look at the SGI docs for the Forward Iterator concept. Nowhere does it say that *it should be a real reference. The docs for Trivial Iterators specifically mention proxy references and say they’re legit.

    Recently, a who’s who of C++ luminaries put their names on N3351, the so-called Palo Alto TR, which proposes a concept-based redesign of the STL, using the syntax of Concepts Lite. Interestingly, the Palo Alto TR is a throw-back to the original SGI design: there is no “true-reference” requirement on the return type of *it; it merely must be convertible to const ValueType<I> &:

    // This must work, according to the Palo Alto TR
    const ValueType<I> & val = *it;
    

    It’s not hard for a proxy reference type to provide such a conversion. For instance, the following compiles today:

    std::vector<bool> vb{true, false, true, false};
    auto it = vb.begin();
    const bool & val = *it;
    

    *it has an implicit conversion to bool, which binds to a const bool&. Awesome! So the problem is solved, right? Not quite.

    A Panoply of Proxy Problems

    To better see the problems with proxy iterators, let’s look at a more interesting example: a zip view. When you zip two sequences together, you get a single sequence where each element is a std::pair of elements from the two source sequences. This can be done lazily, creating pairs on demand as the zip view is iterated:

    std::vector<int> v1 { 1,2,3 };
    std::vector<int> v2 { 9,8,7 };
    
    auto z = view::zip( v1, v2 );
    auto it = z.begin();
    
    assert( *it   == std::make_pair(1,9) );
    assert( *++it == std::make_pair(2,8) );
    assert( *++it == std::make_pair(3,7) );
    

    Since the zip view is generating the pairs on demand, they don’t exist anywhere in memory. But the elements they refer to do! See?

    std::pair<int&,int&> p = *z.begin();
    assert( &p.first  == &v1[0] );
    assert( &p.second == &v2[0] );
    

    The zip view is a very interesting beastie. Its reference type is pair<T&,U&> and its value type is pair<T,U>. This poses some very interesting challenges for the iterator concepts.

    1. Values and References

    Recall that the Palo Alto TR requires *it to be convertible to const ValueType<I>&. So we should be able to do this:

    auto z = view::zip( v1, v2 );
    const pair<int,int>& val = *z.begin();
    

    That works! As it so happens, there is a conversion from std::pair<T&,U&> to std::pair<T,U> — but there’s a catch: it only works if T and U are copyable! And even when they’re not, it’s clear that copying is not the behavior one would expect when using *it to initialize a const reference. If T or U is expensive to copy, you’re not going to get the performance or the behavior you expect, and if it’s unique_ptr it’s not going to compile at all. 🙁

    Requiring that an iterator’s reference type be convertible to const ValueType<I>& is over-constraining. But then what useful thing can we say about the relationship between these two types?

    2. Algorithm Constraints

    All the algorithm signatures in the Palo Alto TR use ValueType in the concept checks in order to constrain the templates. For example, here’s the constrained signature of for_each:

    template<InputIterator I, Semiregular F>
        requires Function<F, ValueType<I>>
    F for_each(I first, I last, F f);
    

    If you’re not familiar with C++ concepts, what lines 1 and 2 say is: first and last must satisfy the requirements of the InputIterator concept, F must be Semiregular (I’ll gloss over this bit), and it must be callable with one argument of the iterator’s value type.

    Now imagine code like this:

    // As before, v1 and v2 are vectors of ints:
    auto z = view::zip( v1, v2 );
    // Let Ref be the zip iterator's reference type:
    using Ref = decltype(*z.begin());
    // Use for_each to increment all the ints:
    for_each( z.begin(), z.end(), [](Ref r) {
        ++r.first;
        ++r.second;
    });
    

    This seems perfectly reasonable. The lambda accepts an object of the zip view’s reference type, which is a pair<int&,int&>, and then it increments both first and second members. But this doesn’t type-check. Why?

    Remember the concept check: Function<F, ValueType<I>>. The function we pass to for_each must be callable with an object of the iterator’s value type. In this case, the value type is pair<int,int>. There is no conversion from that to the type the function expects, which is pair<int&,int&>. Bummer.

    If we change the lambda to take a pair<int,int>&, then the concept check passes, but the template will fail to instantiate correctly. It’s easy to see why when you look at a typical for_each implementation:

    template<InputIterator I, Semiregular F>
    requires Function<F, ValueType<I>>
    F for_each(I first, I last, F f) {
        for(; first != last; ++first)
            f(*first);
        return f;
    }
    

    The lambda is called with *first which has type pair<int&,int&>, but that doesn’t convert to pair<int,int>&. Gah!!!

    The most galling bit is that the code we wrote above — the code with the lambda that takes the reference type — works just fine if we simply delete the requires Function<F, ValueType<I>> constraint. Clearly something is wrong with the constraints, the concepts, or our expectations.

    I should add that the problem is not specific to the zip view. Any sequence with a proxy reference type has this problem, vector<bool> included. If we just slap these constraints on the existing algorithms, some code that works today will break, and the only “fix” would be to stop using the standard algorithms. 🙁

    3. Permutability of Move-Only Types

    Unfortunately, the problems don’t end there. The sort algorithm requires a sequence to be permutable; that is, you should be able to shuffle its elements around. And since it should support move-only types, that means that the sequence’s iterators should be indirectly-movable. The Palo Alto TR has this to say about it:

    The IndirectlyMovable and IndirectlyCopyable concepts describe copy and move relationships between the values of an input iterator, I, and an output iterator Out. For an output iterator out and an input iterator in, their syntactic requirements expand to:

    • IndirectlyMovable requires *out = move(*in)

    But what if *in returns a proxy? Then move(*in) is moving the proxy, not the object to which the proxy refers. In the case of sorting a zip view, we’re trying to move a (temporary) pair<T&,U&> into a pair<T&,U&>. As with issue (1), that won’t work at all for move-only types. But you would probably fail before that, at the sort requires clause, because of issue (2). Sheesh!

    Summary, For Now…

    Even though the Palo Alto TR lifts the over-constraining requirement that ForwardIterators return real references, the proxy iterator problem remains. On the one hand, it says that proxy iterators are OK. On the other hand, some interesting proxy iterators fail to model the Iterator concept or satisfy the algorithm constraints, and those that do don’t have the right semantics or performance characteristics. What are our options?

    1. The zip view, vector<bool>, and its ilk are useful, but are not legitimate containers and ranges, and the STL can’t support them, full stop; or
    2. The iterator concepts (and probably the algorithm constraints) as specified in the Palo Alto TR need to be tweaked somehow to support proxy iterators, and some algorithm implementations probably need to change, too; or
    3. The language needs to change to better support proxy references (an idea from Sean Parent); or
    4. Something else.

    I really don’t like option (1); there are too many interesting forward iterators that can’t return true references, and I’m tired of doing without. I have some rudimentary ideas about option (2) that I plan to describe in my next post. Option (3) can’t be ruled out, but IANALL (I Am Not A Language Lawyer) and have no idea what would be involved. It’s clear that with C++17 shaping up, and with the Concepts Lite TR finally reaching PDTS status , and a range-ified, concept-ified STL in the works, the time to start making decisions about this stuff is now.

    "\e"
  • A Slice of Python in C++

    This post describes a fun piece of hackery that went into my Range-v3 library recently: a Python-like range slicing facility with cute, short syntax. It’s nothing earth-shattering from a functionality point of view, but it’s a fun little case study in library design, and it nicely illustrates my philosophy of library design.

    Python Slicing

    In Python, you can slice a container — that is, create a view of a contiguous subrange — using a very concise syntax. For instance:

    >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> letters
    ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> # access a subrange with a slice operation
    >>> letters[2:5]
    ['c', 'd', 'e']
    >>> # replace some values
    >>> letters[2:5] = ['C', 'D', 'E']
    >>> letters
    ['a', 'b', 'C', 'D', 'E', 'f', 'g']
    

    On line 5, we access elements of the list letters in the half-open sequence [2,5) using the syntax letters[2:5]. Short and sweet. On line 8, we assign through the slice, which mutates the underlying letters list. That proves that Python slices have reference semantics.

    That’s not all that the Python slice operator can do. You can leave off slice offsets, in which case Python takes a smart default:

    >>> # A missing first offset means "from the beginning"
    >>> letters[:5]
    ['a','b','C', 'D', 'E']
    >>> # A missing end offset means "to the end"
    >>> letters[5:]
    ['f','g']
    

    You can even slice from the end with negative offsets:

    >>> # Take the last two elements:
    >>> letters[-2:]
    

    This is all pretty handy and really cool.

    Old-Style Slicing in C++ with Range-v3

    My range-v3 library has had a slice operation for a long time now, but it wasn’t as powerful and the syntax wasn’t as cool:

    using namespace ranges;
    auto letters = view::iota('a','g');
    std::cout << letters << '\n';
    // prints: {a,b,c,d,e,f,g}
    std::cout << (letters | view::slice(2,5)) << '\n';
    // prints: {c,d,e}
    

    In the above code, view::iota is a view that generates all the characters from 'a' to 'g' (inclusive), and view::slice is a view of the elements from offset 2 through 5 (exclusive). As with Python’s slice, this slice is lightweight and non-owning.

    This syntax is not terrible per se, but it’s certainly not as fun as Python’s. And view::slice didn’t accept negative offsets to slice from the end, so it wasn’t as powerful, either.

    New-Style Slicing in C++ with Range-v3

    First, I wanted to find a nice short-form for creating slices, so I took a page from the array_view proposal, which has a really, really clever syntax for indexing into a multi-dimensional array. Here’s an example lifted straight from the proposal:

    char a[3][1][4] {{{'H', 'i'}}};
    auto av = array_view<char, 3>{a};
    // the following assertions hold:
    assert((av.bounds() == bounds<3>{3, 1, 4}));
    assert((av[{0, 0, 0}] == 'H'));
    

    Lines 1-2 declare a 3-D array of characters and then creates a 3-D view of it. Line 5 is where the magic happens. It accesses the element at the (0,0,0) position with the slightly alien-looking av[{0,0,0}] syntax. What the heck is this?!

    It’s really very simple: a novel use of uniform initialization syntax. Consider this type:

    struct indices
    {
        std::size_t i, j, k;
    };
    struct my_array_view
    {
        double & operator[](indices x);
    };
    

    Now I can index into a my_array_view object with the av[{0,0,0}] syntax. Neat-o!

    I realized I could use this trick to give people a super-short and cute syntax for slicing ranges. Check it out:

    using namespace ranges;
    auto letters = view::iota('a','g');
    std::cout << letters << '\n';
    // prints: {a,b,c,d,e,f,g}
    std::cout << letters[{2,5}] << '\n';
    // prints: {c,d,e}
    

    Hey, that’s not half bad!

    Slicing From the End, A Dilemma

    But that’s not enough. I want the handy slice-from-the-end functionality. But here’s where things get a bit … interesting … from a library design perspective. Not all range types support slicing from the end. To see what I mean, consider a range of ints read from an istream. This is an input range. You don’t know the end until you reach it, which means that you don’t know the last-minus-N element until you’re N elements past it!

    In other words, the following code makes no sense:

    using namespace ranges;
    // An input range of ints read from cin
    auto ints = istream<int>(std::cin);
    // I'm sorry, I can't do that, Dave:
    std::cout << ints[{0,-2}] << '\n';
    

    The istream range returned by istream totally knows at compile time that it can’t be sliced from the end. But whether the offsets are negative or positive is a runtime property, so it can’t be checked at compile time. That would make this a runtime failure. Ugh.

    To make matters worse, the rules about what categories of ranges accept negative offsets are surprisingly subtle. Consider this variation of the code above:

    using namespace ranges;
    // Take the first 10 ints read from cin:
    auto ints = istream<int>(std::cin) | view::take(10);
    // This should work! It should take the first 8 ints:
    std::cout << ints[{0,-2}] << '\n';
    

    In this case, we’ve taken the first 10 integers from an istream. The ints range is still an input range, but it’s a sized input range. Now we can slice from the end because we know where the end is.

    And if we have a forward range, we can always slice from the end, even if we don’t know where that is (e.g. a null-terminated string), by computing the length of the sequence and then advancing distance-minus-N from the front (although that’s not always the most efficient way to do it).

    And you should never specify a negative offset if the range is infinite. Never, ever, ever.

    It gets even more subtle still: if both offsets are negative, or if both offsets are non-negative, then the resulting slice knows its size in O(1); otherwise, it only knows its size if the underlying range knows its size. When the O(1)-sized-ness of a range is part of the type system, it enables all sorts of optimizations. If we don’t know the sign of the offsets until runtime, we can’t ever return a type that advertises itself as sized.

    My point is that the rules for when it’s OK to slice from the end are subtle — far too subtle to leave the error reporting until runtime. And doing so leaves valuable optimizations on the floor.

    Slicing From the End, A Solution

    The solution I came up with was to disallow negative offsets with an unconditional assert. But wait before you flame me! I added an alternate syntax for denoting an offset from the end. Check it out:

    using namespace ranges;
    auto letters = view::iota('a','g');
    std::cout << letters << '\n';
    // prints: {a,b,c,d,e,f,g}
    std::cout << letters[{2,end-2}] << '\n';
    // prints: {c,d,e}
    

    Instead of using a negative offset, we say end-2 to mean the 2nd from the end. What is end here? It’s the same end function that you call to get the end of an Iterable (think std::end), only in my library it’s not a function; it’s a function object. (For more about why I chose to make begin and end global function objects instead of free functions, see my blog post about Customization Point Design.) Since end is an object, I can define an overloaded operator- that takes end on the left-hand-side and an int on the right. That can return an object of some type that makes the from-the-end-ness of the offset a part of the type system.

    struct from_end { int i; };
    
    from_end operator-( decltype(ranges::end), int i )
    {
        assert(i >= 0); // No funny business, please
        return {i};
    }
    

    Now I can define an overloaded operator[] on my range type that accepts a std::pair<int,from_end>:

    struct my_range
    {
        // callable as rng[{2,end-2}]
        slice_view<my_range>
        operator[](std::pair<int, from_end> p)
        {
            // ... slicing happens here
        }
    };
    

    Voilà! Now I get slicing from the end with a short, readable syntax and compile-time type checking without leaving any optimization opportunities on the floor.

    Yes, But…

    That’s great and all, but code like “rng[{2,-2}]” still compiles and fails at runtime. How is the situation any better? The difference now is that passing a negative offset to slice is always a runtime error. There is no situation in which it will succeed and do what you want, even if the range type could conceivably support it. Users will quickly learn that that isn’t the way to do it.

    Had we allowed negative offsets in a way that sometimes worked and sometimes didn’t, it makes the interface far more dangerous. Users will try it, meet with some success, and conclude incorrectly that it will always work. They’ll discover their error the hard way after their application has been deployed.

    Which brings me to my Philosophy of Library Design:

    I can’t keep people from writing bad code. But I’m guilty of collusion if I make it easy.

    And a corollary that relates to this problem:

    If you can’t make something succeed consistently, it’s better to make it fail consistently.

    Hope you enjoyed this little case study in library design.

    Acknowledgements

    I’d like to thank Chandler Carruth for drawing my attention to the pithy coolness of Python’s slice operator.

    Footnote:

    In the C++ containers, the indexing operation is only allowed for random-access containers, where the element can be accessed in O(1). Here, I’m allowing users to slice ranges with an indexing-like notation, even though it could be an O(N) operation. I’m currently undecided if slicing is sufficiently different from indexing to justify this decision. Thoughts welcome.

    "\e"
    "\e"
  • Container Algorithms

    The recent meeting of the C++ Standardization Committee in Urbana-Champaign was a watershed moment for my work on ranges. Ultimately, my presentation was well received (Herb Sutter used the phrase “palpable excitement” to describe the feeling in the room), but it wasn’t at all certain that things would go that way, and in fact an eleventh-hour addition pushed the proposal over the top: container algorithms.

    Ranges, as of N4128

    The existing algorithms in the C++ standard library operate eagerly. After std::transform returns, for instance, you can be sure that all the transform-y stuff is done. Some algorithms are also mutating. When you call std::sort, the data has been sorted — in place.

    Not so with the range views that N4128 proposes. These are like lazily-evaluated, non-mutating algorithms that present custom views of data stored elsewhere. For instance, when you say:

    std::vector<int> ints{1,2,3,4};
    auto squared = ints
        | view::transform([](int i){return i*i;});
    

    … not one iota of transforming has happened. You have just created a view that, when it’s iterated, does transformation on-the-fly, without mutating the underlying sequence.

    The algorithms and the views differ in another important way: the views easily compose — filter a transformed slice? No problem! — but the algorithms don’t. Doing that sort of thing with the algorithms requires fiddling about with iterators and named temporaries, and takes several lines of chatty code.

    The Missing Piece

    So to sum up, in the world of N4128, we have this:

    1. Eager algorithms that can mutate but that don’t compose.
    2. Lazy algorithms that can’t mutate but do compose.
    3. ??!!!!

    Whoops! Something is missing. If I want to read a bunch of ints, sort them, and make them unique, here’s what that would look like in N4128:

    extern std::vector<int> read_ints();
    std::vector<int> ints = read_ints();
    std::sort(ints);
    auto i = std::unique(ints);
    ints.erase(i, ints.end());
    

    Blech! A few people noticed this shortcoming of my proposal. A week before the meeting, I was seriously worried that this issue would derail the whole effort. I needed a solution, and quick.

    Container Algorithms

    The solution I presented in Urbana is container algorithms. These are composable algorithms that operate eagerly on container-like things, mutating them in-place, then forwarding them on for further processing. For instance, the read+sort+unique example looks like this with container algorithms:

    std::vector<int> ints =
        read_ints() | cont::sort | cont::unique;
    

    Much nicer. Since the container algorithm executes eagerly, it can take a vector and return a vector. The range views can’t do that.

    A Moving Example

    Move semantics makes all of this work smoothly. A temporary container is moved into a chain of mutating container algorithms, where it is munged and moved out, ready to be slurped up by the next container algorithm. (Naturally, performance would suffer if container algorithms were used with a container that wasn’t efficiently movable, like a big std::array. Don’t do that.)

    Since container algorithms accept and return containers by value, I worried that people might do this and be surprised by the result:

    std::vector<int> v{/*...*/};
    // Oops, this doesn't sort v:
    v | cont::sort;
    

    The author of this code might expect this to sort v. Instead, v would be copied, the copy would be sorted, and then the result would be ignored.

    Also, there’s a potential performance bug in code like below if we allow people to pass lvalues to container algorithms:

    // Oops, this isn't very efficient:
    std::vector<BigObject> bigvec{/*...*/};
    bigvec = bigvec | cont::sort | cont::unique;
    

    bigvec is copied when it’s passed to cont::sort by value. That’s bad! The alternative would be to have container algorithms do perfect forwarding — in which case what gets returned is a reference to bigvec. That then gets assigned back to bigvec! Assigning a container to itself is … weird. It’s guaranteed to work, but it’s not guaranteed to be efficient. An interface that makes it easy to make this mistake is a bad interface.

    Instead, in my current thinking, the above code should fail to compile. The container algorithms require rvalue containers; you should move or copy a container into the chain. With range-v3, that looks like this:

    using namespace ranges;
    bigvec = std::move(bigvec) | cont::sort | cont::unique;
    

    That fixes the performance problem, and also makes it pretty obvious that you ignore the return type of move(v) | cont::sort at your own peril.

    I also offer this short form to apply a chain of mutating operations to a container:

    bigvec |= cont::sort | cont::unique;
    

    If you’re not a fan of the pipe syntax, this works too:

    cont::unique(cont::sort(bigvec));
    

    Both of these syntaxes will refuse to operate on temporary containers.

    What is a Container?

    Consider this line of code from above, which applies a chain of mutating operations to a container:

    bigvec |= cont::sort | cont::unique;
    

    How is this implemented? One simple answer is to make it a synonym for the following:

    bigvec = std::move(bigvec) | cont::sort | cont::unique;
    

    But not all containers are efficiently movable, so this would be needlessly inefficient. Instead, what gets passed around is a reference-wrapped container. Essentially, it’s implemented like this:

    std::ref(bigvec) | cont::sort | cont::unique;
    

    But cont::sort and cont::unique are container algorithms. Is a reference-wrapped container also a container, then? Un-possible!

    Containers own their elements and copy them when the container is copied. A reference-wrapped container doesn’t have those semantics. It’s a range: an Iterable object that refers to elements stored elsewhere. But ref(v) | cont::sort sure seems like a reasonable thing to do.

    In other words, container algorithms are misnamed! They work just fine when they are passed ranges, so long as the range provides the right operations. cont::sort needs an Iterable with elements it can permute, and that’s it. It doesn’t care at all who owns the elements.

    cont::unique is also indifferent to element ownership, so long as it has a way to remove the non-unique elements. Rather than relying on an erase member function to do the erasing, we can define erase as a customization point — a free function — that any Iterable type can overload. With the appropriate overload of erase for reference-wrapped containers, std::ref(v) | cont::unique will Just Work.

    The interesting (to me, at least) result of this is that containers are not interesting. Instead, we get much farther with refinements of the Iterable concept that add specific behaviors, like EraseableIterable. The container algorithms accept any Iterable that offers the right set of behaviors. They don’t care one whit who owns the elements.

    Summary

    Over the past month, I’ve been adding a full suite of container algorithms to my range-v3 library for things like sorting, removing elements, slicing, inserting, and more. These are eager algorithms that compose. I call them “container algorithms” since “eager, composable algorithms” doesn’t roll off the tongue — they are perfectly happy working ranges. If you want to send a non-owning slice view to cont::sort, knock yourself out.

    Container algorithms fill a gaping hole in N4128. They went a long, long way to appeasing many of the committee members who dearly want ranges to solve the usability problems with the current standard algorithms. I can only assume that, had I left container algorithms out of my presentation, the reception in Urbana would have been a few degrees colder.

    Acknowledgements

    The design of container algorithms presented here benefited tremendously by feedback from Sean Parent.

    UPDATE:

    I’ve heard you! “Container algorithm” is a confusing name. They aren’t restricted to containers, and that isn’t the interesting bit anyway. The interesting bit is that they are eager, mutating, composable algorithms. There is no one pithy word that conveys all of that (AFAICT), but so far “action” has come closest. So we now have view::transform (lazy, non-mutating) and action::transform (eager, mutating). Not perfect, but better, certainly.

    "\e"
  • Ranges, Concepts, and the Future of the Standard Library

    Frequent readers of this blog know that over the past year, I’ve been working on a modern range library suitable for standardization, integrating good ideas from hither and thither — particularly from Sean Parent and Andrew Sutton — resulting in a library that’s available immediately, and a proposal to the standardization committee. This week I presented my work to the C++ Committee Meeting in Urbana-Champaign. The ensuing the discussion has implications for the future of the Standard Library.

    Ranges Evening Session

    I presented my ranges work on Wednesday evening to about 60 committee members. I’m happy to report that it was very warmly received. The committee liked the design of my ranges library and wants to see it in a standard ASAP. The feeling of the group was that the changes were big enough that they wanted them in a separate document known as a TS or a Technical Specification rather than in the official C++ standard. That way, we can flush out potential problems before baking it.

    Some people might be disappointed that ranges will not be in C++17, but let me assure you that this is a Very Good Thing. Vendors have been proactive about implementing and shipping TS’s quickly, and there’s a chance we might get ranges into users’ hands more quickly this way. It also means that since we’re targeting a TS, we can be far more ambitious. Had we tried to squeeze this into C++17, we would have had to gut the proposal and standardize a very small, very conservative subset of functionality. By going the TS route, we can get much more cool stuff out the door much faster, and ship incremental updates as they become ready.

    If any part of the Ranges TS looks especially promising and noncontroversial, it can be air-lifted into C++17.

    The Future of the Standard Library

    With the dawn of Concepts Lite as a language feature, the next obvious step is to use the feature to improve the Standard Library. During the ranges discussion, it seemed generally accepted that it will be impossible (or at least very undesirable) to add concepts to the library in a way that doesn’t break somebody’s code. The committee hates to break working code. One possibility would be to ship a new version of the library alongside the old. Users could then migrate at their leisure. That possibility was openly discussed to much head-nodding.

    If that happens, we would be free to make changes to the Standard Library, not only to leverage Concepts Lite but also to support ranges, increase uniformity and expressive power, ease-of-use, safety, and to fix some long-standing issues. Whatever we end up with would look a lot like the current Standard Library, and of course existing code would continue to work.

    Let me emphasize that this is my opinion of the general feeling in the room. The committee has not voted on this. What is clear is that work will now begin on a version of the STL that uses Concepts Lite and that looks a lot like my range-v3 library, and that this version will not make a priority of perfect backwards compatibility. That work will go into a Technical Specification, and vendors will start shipping it in a std::experimental namespace as soon as it hits the presses. I couldn’t be more excited!

    Edited to clarify what is my opinion and what is a possible future.

  • Ranges in C++: Counted Iterables and Efficiency

    I’ve been hard at work fleshing out my range library and writing a proposal to get range support into the standard. That proposal describes a foundational range concept: Iterable. An Iterable is anything we can pass to std::begin() and std::end() to get an Iterator/Sentinel pair. Sentinels, as I described here earlier this year, make it possible for the Iterable concept to efficiently describe other kinds of ranges besides iterator pairs.

    The three types of ranges that we would like the Iterable concept to be able to efficiently model are:

    1. Two iterators
    2. An iterator and a predicate
    3. An iterator and a count

    The Iterator/Sentinel abstraction is what makes it possible for the algorithms to handle these three cases with uniform syntax. However, as Sean Parent pointed out here, the third option presents challenges when trying to make some algorithms optimally efficient. Back in February, when Sean offered his criticism, I promised to follow up with a blog post that justified the design. This is that post.

    Note 1: I’ve changed terminology since the February posts. In those posts, Iterable represented a range where the begin and end have different types, and Range is an Iterable where they’re the same. In my current proposal, Iterable is more or less as it was before, but Range is now an Iterable that doesn’t own its elements.

    Note 2: This post uses the syntax of Concepts Lite, which has not been adopted yet. Everything in this post is implementable in C++11 using my library for Concepts Lite emulation, which I describe here.

    Counted Ranges

    Counted ranges, formed by specifying a position and a count of elements, have iterators — as all Iterables do. The iterators of a counted range must know the range’s extent and how close they are to reaching it. Therefore, the counted range’s iterators must store both an iterator into the underlying sequence and a count — either a count to the end or a count from the front. Here is one potential design:

    class counted_sentinel
    {};
    
    template<WeakIterator I>
    class counted_iterator
    {
        I it_;
        DistanceType<I> n_; // distance to end
    public:
        // ... constructors...
        using iterator_category =
            typename iterator_traits<I>::iterator_category;
        decltype(auto) operator*() const
        {
            return *it_;
        }
        counted_iterator & operator++()
        {
            ++it_;
            --n_;
            return *this;
        }
        friend bool operator==(counted_iterator const & it,
                               counted_sentinel)
        {
            return it.n_ == 0;
        }
        // ... other operators...
    };
    
    template<WeakIterator I>
    class counted_range
    {
        I begin_;
        DistanceType<I> count_;
    public:
        // ... constructors ...
        counted_iterator<I> begin() const
        {
            return {begin_, count_};
        }
        counted_sentinel end() const
        {
            return {};
        }
    };
    

    There are some noteworthy things about the code above. First, counted_iterator bundles an iterator and a count. Right off, we see that copying counted iterators is going to be more expensive, and iterators are copied frequently. A mitigating factor is that the sentinel is empty. Passing a counted_iterator and a counted_sentinel to an algorithm copies as much data as passing an iterator and a count. When passed separately, the compiler probably has an easier time fitting them in registers, but some modern compilers are capable passing the members of a struct in registers. This compiler optimization is sometimes called Scalar Replacement of Aggregates1, 2 and is known to be implemented in gcc and LLVM (see this recent LLVM commit for example).

    Also, incrementing a counted iterator is expensive: it involves incrementing the underlying iterator and decrementing the internal count. To see why this is potentially expensive, consider the trivial case of passing a counted_iterator<list<int>::iterator> to advance. That counted iterator type is bidirectional, and advance must increment it n times:

    template<BidirectionalIterator I>
    void advance(I & i, DistanceType<I> n)
    {
        if(n >= 0)
            for(; n != 0; --n)
                ++i;
        else
            for(; n != 0; ++n)
                --i;
    }
    

    Notice that for each ++i or --i here, two increments or decrements are happening when I is a counted_iterator. This is sub-optimal. A better implementation for counted_iterator is:

    template<BidirectionalIterator I>
    void advance(counted_iterator<I> & i, DistanceType<I> n)
    {
        i.n_ -= n;
        advance(i.it_, n);
    }
    

    This has a noticeable effect on the generated code. As it turns out, advance is one of the relatively few places in the standard library where special handling of counted_iterator is advantageous. Let’s examine some algorithms to see why that’s the case.

    Single-Pass Algorithms with Counted Iterators

    First, let’s look at a simple algorithm like for_each that makes exactly one pass through its input sequence:

    template<InputIterator I, Regular S,
             Function<ValueType<I>> F>
        requires EqualityComparable<I, S>
    I for_each(I first, S last, F f)
    {
        for(; first != last; ++first)
            f(*first);
        return first;
    }
    

    When passed counted iterators, at each iteration of the loop, we do an increment, a decrement (for the underlying iterator and the count), and a comparison. Let’s compare this against a hypothetical for_each_n algorithm that takes the underlying iterator and the count separately. It might look like this:

    template<InputIterator I, Function<ValueType<I>> F>
    I for_each_n(I first, DifferenceType<I> n, F f)
    {
        for(; n != 0; ++first, --n)
            f(*first);
        return first;
    }
    

    For the hypothetical for_each_n, at each loop iteration, we do an increment, a decrement, and a comparison. That’s exactly as many operations as for_each does when passed counted iterators. So a separate for_each_n algorithm is probably unnecessary if we have sentinels and counted_iterators. This is true for any algorithm that makes only one pass through the input range. That turns out to be a lot of algorithms.

    Multi-Pass Algorithms with Counted Iterators

    There are other algorithms that make more than one pass over the input sequence. Most of those, however, use advance when they need to move iterators by more than one hop. Once we have specialized advance for counted_iterator, those algorithms that use advance get faster without any extra work.

    Consider partition_point. Here is one example implementation, taken from libc++ and ported to Concepts Lite and sentinels:

    template<ForwardIterator I, Regular S,
             Predicate<ValueType<I>> P>
        requires EqualityComparable<I, S>
    I partition_point(I first, S last, P pred)
    {
        DifferenceType<I> len = distance(first, last);
        while (len != 0)
        {
            DifferenceType<I> l2 = len / 2;
            I m = first;
            advance(m, l2);
            if (pred(*m))
            {
                first = ++m;
                len -= l2 + 1;
            }
            else
                len = l2;
        }
        return first;
    }
    

    Imagine that I is a forward counted_iterator and S is a counted_sentinel. If the library does not specialize advance, this is certainly inefficient. Every time advance is called, needless work is being done. Compare it to a hypothetical partition_point_n:

    template<ForwardIterator I, Predicate<ValueType<I>> P>
    I partition_point_n(I first, DifferenceType<I> len, P pred)
    {
        while (len != 0)
        {
            DifferenceType<I> l2 = len / 2;
            I m = first;
            advance(m, l2);
            if (pred(*m))
            {
                first = ++m;
                len -= l2 + 1;
            }
            else
                len = l2;
        }
        return first;
    }
    

    The first thing we notice is that partition_point_n doesn’t need to call distance! The more subtle thing to note is that calling partition_point_n with a raw iterator and a count saves about O(N) integer decrements over the equivalent call to partition_point with counted_iterators … unless, of course, we have specialized the advance algorithm as shown above. Once we have, we trade the O(N) integer decrements for O(log N) integer subtractions. That’s a big improvement.

    But what about the O(N) call to distance? Actually, that’s easy, and it’s the reason why I introduced a concept called SizedIteratorRange. counted_iterator stores the distance to the end. So the distance between a counted_iterator and a counted_sentinel (or between two counted_iterators) is known in O(1) regardless of the iterator’s category. The SizedIteratorRange concept tests whether an iterator I and a sentinel S can be subtracted to get the distance. This concept is modeled by random-access iterators by their nature, but also by counted iterators and their sentinels. The distance algorithm is specialized for SizedIteratorRange, so it is O(1) for counted iterators.

    With these changes, we see that partition_point with counted iterators is very nearly as efficient as a hypothetical partition_point_n would be, and we had to make no special accommodations. Why can’t we make partition_point exactly as efficient as partition_point_n? When partition_point is called with a counted iterator, it also returns a counted iterator. Counted iterators contain two datums: the position and distance to the end. But when partition_point_n returns just the position, it is actually computing and returning less information. Sometimes users don’t need the extra information. But sometimes, after calling partition_point_n, the user might want to pass the resulting iterator to another algorithm. If that algorithm calls distance (like partition_point and other algorithms do), then it will be O(N). With counted iterators, however, it’s O(1). So in the case of partition_point, counted iterators cause the algorithm to do O(log N) extra work, but it sometimes saves O(N) work later.

    To see an example, imagine a trivial insertion_sort algorithm:

    template<ForwardIterator I, Regular S>
        requires EqualityComparable<I, S> &&
                 Sortable<I> // from N3351
    void insertion_sort(I begin, S end)
    {
        for(auto it = begin; it != end; ++it)
        {
            auto insertion = upper_bound(begin, it, *it);
            rotate(insertion, it, next(it));
        }
    }
    

    Imagine that I is a counted_iterator. The first thing upper_bound does is call distance. Making distance O(1) for counted_iterators saves N calls of an O(N) algorithm. To get comparable performance for an equivalent procedure in today’s STL, users would have to write a separate insertion_sort_n algorithm that dispatches to an upper_bound_n algorithm — that they would also need to write themselves.

    Counted Algorithms with Counted Iterators

    We’ve seen that regular algorithms with counted iterators can be made nearly as efficient as dedicated counted algorithms, and that sometimes we are more than compensated for the small performance loss. All is not roses, however. There are a number of counted algorithms in the standard (the algorithms whose names end with _n). Consider copy_n:

    template<WeakInputIterator I,
             WeakOutputIterator<ValueType<I>> O>
    pair<I, O> copy_n(I in, DifferenceType<I> n, O out)
    {
        for(; n != 0; ++in, ++out, --n)
            *out = *in;
        return {in, out};
    }
    

    (We’ve changed the return type of copy_n so as not to lose information.) If I is a counted iterator, then for every ++in, an increment and a decrement are happening, and in this case the extra decrement is totally unnecessary. For any counted (i.e., _n) algorithm, something special needs to be done to keep the performance from degrading when passed counted iterators.

    The algorithm author has two options here, and neither of them is ideal.

    Option 1: Overload the algorithm

    The following is an optimized version of copy_n for counted iterators:

    template<WeakInputIterator I,
             WeakOutputIterator<ValueType<I>> O>
    pair<I, O> copy_n(counted_iterator<I> in,
                      DifferenceType<I> n, O out)
    {
        for(auto m = in.n_ - n; in.n_ != m;
                ++in.i_, --in.n_, ++out)
            *out = *in;
        return {in, out};
    }
    

    Obviously, creating an overload for counted iterators is unsatisfying.

    Option 2: Separate the iterator from the count

    This option shows how a library implementer can write just one version of copy_n that is automatically optimized for counted iterators. First, we need to provide two utility functions for unpacking and repacking counted iterators:

    template<WeakIterator I>
    I uncounted(I i)
    {
        return i;
    }
    
    template<WeakIterator I>
    I uncounted(counted_iterator<I> i)
    {
        return i.it_;
    }
    
    template<WeakIterator I>
    I recounted(I const &, I i, DifferenceType<I>)
    {
        return i;
    }
    
    template<WeakIterator I>
    counted_iterator<I> recounted(counted_iterator<I> const &j, I i, DifferenceType<I> n)
    {
        return {i, j.n_ - n};
    }
    

    With the help of uncounted and recounted, we can write an optimized copy_n just once:

    template<WeakInputIterator I,
             WeakOutputIterator<ValueType<I>> O>
    pair<I, O> copy_n(I in_, DifferenceType<I> n_, O out)
    {
        auto in = uncounted(in_);
        for(auto n = n_; n != 0; ++in, --n, ++out)
            *out = *in;
        return {recounted(in_, in, n_), out};
    }
    

    This version works optimally for both counted and non-counted iterators. It is not a thing of beauty, however. It’s slightly annoying to have to do the uncounted/recounted dance, but it’s mostly needed only in the counted algorithms.

    As a final note, the overload of advance for counted iterators can be eliminated with the help of uncounted and recounted. After all, advance is a counted algorithm.

    Benchmark: Insertion Sort

    To test how expensive counted ranges and counted iterators are, we wrote a benchmark. The benchmark pits counted ranges against a dedicated _n algorithm for Insertion Sort. The program is listed in this gist.

    The program implements both insertion_sort_n, a dedicated counted algorithm, and insertion_sort, a general algorithm that accepts any Iterable, to which we pass a counted range. The latter is implemented in terms of the general-purpose upper_bound as provided by the Range v3 library, whereas the former requires a dedicated upper_bound_n algorithm, which is also provided.

    The test is run both with raw pointers (hence, random-access) and with an iterator wrapper that only models ForwardIterator. Each test is run three times, and the resulting times are averaged. The test was compiled with g++ version 4.9.0 with -O3 -std=gnu++11 -DNDEBUG and run on a Linux machine. The results are reported below, for N == 30,000:

    insertion_sort_n insertion_sort
    random-access 2.692 s 2.703 s
    forward 23.853 s 23.817 s

    The performance difference, if there is any, is lost in the noise. At least in this case, with this compiler, on this hardware, there is no performance justification for a dedicated _n algorithm.

    Summary

    In short, counted iterators are not a perfect abstraction. There is some precedent here. The iterators for deque, and for any segmented data structure, are known to be inefficient (see Segmented Iterators and Hierarchical Algorithms, Austern 1998). The fix for that problem, new iterator abstractions and separate hierarchical algorithm implementations, is invasive and is not attempted in any STL implementation I am aware of. In comparison, the extra complications that come with counted iterators seem quite small. For segmented iterators, the upside was the simplicity and uniformity of the Iterator abstraction. In the case of counted ranges and iterators, the upside is the simplicity and uniformity of the Iterable concept. Algorithms need only one form, not separate bounded, counted, and sentinel forms. The benchmark gives me some reasonable assurance that we aren’t sacrificing too much performance for the sake of a unifying abstraction.

    "\e"
    "\e"