Author: Eric Niebler

  • 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"
  • Tiny Metaprogramming Library

    (Difficult-to-grok metaprogramming below. Not for the faint of heart.)

    At the recent Urbana-Champaign meeting of the C++ Standardization Committee, Bill Seymour presented his paper N4115: Searching for Types in Parameter Packs which, as its name suggests, describes a library facility for, uh, searching for a type in a parameter pack, among other things. It suggests a template called packer to hold a parameter pack:

    // A class template that just holds a parameter pack:
    template <class... T> struct packer { };
    

    Many of you are probably already familiar with such a facility, but under a different name:

    // A class template that is just a list of types:
    template <class... T> struct typelist { };
    

    It became clear in the discussion about N4115 that C++ needs a standard typelist template and some utilities for manipulating them. But what utilities, exactly?

    Metaprogramming in the Wild

    When it comes to metaprogramming in C++, there is no shortage of prior art. Andrei Alexandrescu started the craze with his Loki library. Boost got in on the act with Boost.MPL, Boost.Fusion, and (currently under development) Hana. All of these libraries are feature-rich and elaborate with their own philosophy, especially Boost.MPL, which takes inspiration from the STL’s containers, iterators, and algorithms.

    It wasn’t until recently that I came to doubt MPL’s slavish aping of the STL’s design. The abstractions of the STL were condensed from real algorithms processing real data structures on real computer hardware. But metaprograms don’t run on hardware; they run on compilers. The algorithms and data structures for our metaprograms should be tailored to their peculiar problem domain and execution environment. If we did that exercise, who is to say what abstractions would fall out? Compile-time iterators? Or something else entirely?

    Dumb Typelists

    If we were to standardize some metaprogramming facilities, what should they look like? It’s an interesting question. N4115 gets one thing right: parameter packs are the compile-time data structure of choice. As of C++11, C++ has language support for lists of types. We would be foolish to work with anything else. IMO, if a standard metaprogramming facility did nothing but manipulate parameter packs — dumb typelists — it would cover 95% of the problem space.

    But parameter packs themselves are not first-class citizens of the language. You can’t pass a parameter pack to a function without expanding it, for instance. Wrapping the parameter pack in a variadic typelist template is a no-brainer.

    So, like N4115 suggests, this is a sensible starting point:

    // A class template that just a list of types:
    template <class... T> struct typelist { };
    

    It’s a rather inauspicious start, though; clearly we need more. But what? In order to answer that, we need to look at examples of real-world metaprogramming. With concrete examples, we can answer the question, What he heck is this stuff good for, anyway? And for examples, we have to look no farther than the standard library itself.

    Tuple_cat

    Stephan T. Lavavej drew my attention to the tuple_cat function in the standard library, a function that takes N tuples and glues them together into one. It sounds easy, but it’s tricky to code efficiently, and it turns out to be a great motivating example for metaprogramming facilities. Let’s code it up, and posit a few typelist algorithms to make our job easier. (All the code described here can be found in my range-v3 library on GitHub.)

    First, I’m going to present the final solution so you have an idea of what we’re working toward. Hopefully, by the time you make it to the end of this post, this will make some sort of sense.

    namespace detail
    {
        template<typename Ret, typename...Is, typename ...Ks,
            typename Tuples>
        Ret tuple_cat_(typelist<Is...>, typelist<Ks...>,
            Tuples tpls)
        {
            return Ret{std::get<Ks::value>(
                std::get<Is::value>(tpls))...};
        }
    }
    
    template<typename...Tuples,
        typename Res =
            typelist_apply_t<
                meta_quote<std::tuple>,
                typelist_cat_t<typelist<as_typelist_t<Tuples>...> > > >
    Res tuple_cat(Tuples &&... tpls)
    {
        static constexpr std::size_t N = sizeof...(Tuples);
        // E.g. [0,0,0,2,2,2,3,3]
        using inner =
            typelist_cat_t<
                typelist_transform_t<
                    typelist<as_typelist_t<Tuples>...>,
                    typelist_transform_t<
                        as_typelist_t<make_index_sequence<N> >,
                        meta_quote<meta_always> >,
                    meta_quote<typelist_transform_t> > >;
        // E.g. [0,1,2,0,1,2,0,1]
        using outer =
            typelist_cat_t<
                typelist_transform_t<
                    typelist<as_typelist_t<Tuples>...>,
                    meta_compose<
                        meta_quote<as_typelist_t>,
                        meta_quote_i<std::size_t, make_index_sequence>,
                        meta_quote<typelist_size_t> > > >;
        return detail::tuple_cat_<Res>(
            inner{},
            outer{},
            std::forward_as_tuple(std::forward<Tuples>(tpls)...));
    }
    

    That’s only 43 lines of code. The implementation in stdlib++ is 3x longer, no easier to understand (IMHO), and less efficient. There’s real value in this stuff. Really.

    Let’s look first at the return type:

    // What return type???
    template< typename ...Tuples >
    ???? tuple_cat( Tuples &&... tpls );
    

    You can think of a tuple as a list of types and a list of values. To compute the return type, we only need the list of types. So a template that turns a tuple into a typelist would be useful. Let’s call it as_typelist. It takes a tuple and does the obvious. (Another possibility would be to make tuples usable as typelists, but let’s go with this for now.)

    If we convert all the tuples into typelists, we end up with a list of typelists. Now, we want to concatenate them. Ah! We need an algorithm for that. Let’s call it typelist_cat in honor of tuple_cat. (Functional programmers: typelist_cat is join in the List Monad. Shhh!! Pass it on.) Here’s what we have so far:

    // Concatenate a typelist of typelists
    template< typename ...Tuples >
    typelist_cat_t<
        typelist< as_typelist_t< Tuples >... >
    >
    tuple_cat( Tuples &&... tpls );
    

    Here, I’m following the convention in C++14 that some_trait_t<X> is a template alias for typename some_trait<X>::type.

    The above signature isn’t right yet — tuple_cat needs to return a tuple, not a typelist. We need a way to convert a typelist back to a tuple. It turns out that expanding a typelist into a variadic template is a useful operation, so let’s create an algorithm for it. What should it be called? Expanding a typelist into a template is a lot like expanding a tuple into a function call. There’s a tuple algorithm for that in the Library Fundamentals TS called apply. So let’s call our metafunction typelist_apply. It’s implementation is short and interesting, so I’ll show it here:

    template<template<typename...> class C, typename List>
    struct typelist_apply;
    
    template<template<typename...> class C, typename...List>
    struct typelist_apply<C, typelist<List...>>
    {
        using type = C<List...>;
    };
    

    The first parameter is a rarely-seen template template parameter. We’ll tweak this interface before we’re done, but this is good enough for now.

    We can now write the signature of tuple_cat as:

    template<typename...Tuples>
    typelist_apply_t<
        std::tuple,
        typelist_cat_t<typelist<as_typelist_t<Tuples>...> > >
    tuple_cat(Tuples &&... tpls);
    

    Not bad, and we have discovered three typelist algorithms already.

    Tuple_cat Implementation

    It’s time to implement tuple_cat, and here’s where things get weird. It’s possible to implement it by peeling off the first tuple and exploding it into the tail of a recursive call. Once you’ve recursed over all the tuples in the argument list, you have exploded all the tuple elements into function arguments. From there, you bundle them into a final tuple and you’re done.

    That’s a lot of parameter passing.

    Stephan T. Lavavej tipped me off to a better way: Take all the tuples and bundle them up into a tuple-of-tuples with std::forward_as_tuple. Since tuples are random-access, a tuple of tuples is like a jagged 2-dimensional array of elements. We can index into this 2-dimensional array with (i,j) coordinates, and if we have the right list of (i,j) pairs, then we can fetch each element in turn and build the resulting tuple in one shot, without all the explosions.

    To make this more concrete, imaging the following call to tuple_cat:

    std::tuple<int, short, long> t1;
    std::tuple<> t2;
    std::tuple<float, double, long double> t3;
    std::tuple<void*, char*> t4;
    
    auto res = tuple_cat(t1,t2,t3,t4);
    

    We want the result to be a monster tuple of type:

    std::tuple<int, short, long, float, double,
               long double, void*, char*>
    

    This call to tuple_cat corresponds to the following list of (i,j) coordinates:

    [(0,0),(0,1),(0,2),(2,0),(2,1),(2,2),(3,0),(3,1)]
    

    Below is a tuple_cat_ helper function that takes the i‘s, j‘s, and tuple of tuples, and builds the resulting tuple:

    template<typename Ret, typename...Is, typename ...Js,
        typename Tuples>
    Ret tuple_cat_(typelist<Is...>, typelist<Js...>,
        Tuples tpls)
    {
        return Ret{std::get<Js::value>(
            std::get<Is::value>(tpls))...};
    }
    

    Here, the Is and Js are instances of std::integral_constant. Is contains the sequence [0,0,0,2,2,2,3,3] and Js contains [0,1,2,0,1,2,0,1].

    Well and good, but how to compute Is and Js? Hang on tight, because Kansas is going bye bye.

    Higher-Order Metaprogramming, Take 1

    Let’s first consider the sequence of Js since that’s a little easier. Our job is to turn a list of typelists [[int,short,long],[],[float,double,long double],[void*,char*]] into a list of integers [0,1,2,0,1,2,0,1]. We can do it in four stages:

    1. Transform the lists of typelist into a list of typelist sizes: [3,0,3,2],
    2. Transform that to a list of index sequences [[0,1,2],[],[0,1,2],[0,1]] using std::make_index_sequence,
    3. Transform the std::index_sequence into a typelist of std::integral_constants with as_typelist, and
    4. Flatten that into the final list using typelist_cat.

    By now it’s obvious that we’ve discovered our fourth typelist algorithm: typelist_transform. Like std::transform, typelist_transform takes a sequence and a function, and returns a new sequence where each element has been transformed by the function. (Functional programmers: it’s fmap in the List Functor). Here’s one possible implementation:

    template<typename List, template<class> class Fun>
    struct typelist_transform;
    
    template<typename ...List, template<class> class Fun>
    struct typelist_transform<typelist<List...>, Fun>
    {
        using type = typelist<Fun<List>...>;
    };
    

    Simple enough.

    Metafunction Composition

    Above, we suggested three consecutive passes with typelist_transform. We can do this all in one pass if we compose the three metafunctions into one. Metafunction composition seems like a very important utility, and it’s not specific to typelist manipulation. So far, we’ve been using template template parameters to pass metafunctions to other metafunctions. What does metafunction composition look like in that world? Below is a higher-order metafunction called meta_compose that composes two other metafunctions:

    template<template<class> class F0,
             template<class> class F1>
    struct meta_compose
    {
        template<class T>
        using apply = F0<F1<T>>;
    };
    

    Composing two metafunction has to result in a new metafunction. We have to use an idiom to “return” a template by defining a nested template alias apply which does the composition.

    Seems simple enough, but in practice, this quickly becomes unwieldy. If you want to compose three metafunctions, the code looks like:

    meta_compose<F0, meta_compose<F1, F2>::template apply>
        ::template apply
    

    Gross. What’s worse, it’s not very general. We want to compose std::make_index_sequence, and that metafunction doesn’t take a type; it takes an integer. We can’t pass it to to a meta_compose. Let’s back up.

    Higher-Order Metaprogramming, Take 2

    What if, instead of passing meta_compose<X,Y>::template apply to a higher-order function like typelist_transform, we just passed meta_compose<X,Y> and let typelist_transform call the nested apply? Now, higher-order functions like typelist_transform take ordinary types instead of template template parameters. typelist_transform would now look like:

    template<typename ...List, typename Fun>
    struct typelist_transform<typelist<List...>, Fun>
    {
        using type =
            typelist<typename Fun::template apply<List>...>;
    };
    

    That complicates the implementation of typelist_transform, but makes the interface much nicer to deal with. The concept of a class type that behaves like a metafunction comes from Boost.MPL, which calls it a Metafunction Class.

    We can make Metafunction Classes easier to deal with with a little helper that applies the nested metafunction to a set of arguments:

    template<typename F, typename...As>
    using meta_apply = typename F::template apply<As...>;
    

    With meta_apply, we can rewrite typelist_transform as:

    template<typename ...List, typename Fun>
    struct typelist_transform<typelist<List...>, Fun>
    {
        using type = typelist<meta_apply<Fun, List>...>;
    };
    

    That’s not bad at all. Now we can change meta_compose to also operate on Metafunction Classes:

    template<typename F1, typename F2>
    struct meta_compose
    {
        template<class T>
        using apply = meta_apply<F1, meta_apply<F2, T>>;
    };
    

    With a little more work, we could even make it accept an arbitrary number of Metafunction Classes and compose them all. It’s a fun exercise; give it a shot.

    Lastly, now that we have Metafunction Classes, we should change typelist_apply to take a Metafunction Class instead of a template template parameter:

    template<typename C, typename...List>
    struct typelist_apply<C, typelist<List...> >
    {
        using type = meta_apply<C, List...>;
    };
    

    Metafunctions to Metafunction Classes

    Recall the four steps we’re trying to evaluate:

    1. Transform the lists of typelist into a list of typelist sizes: [3,0,3,2],
    2. Transform that to a list of index sequences [[0,1,2],[],[0,1,2],[0,1]] using std::make_index_sequence,
    3. Transform the std::index_sequence into a typelist of std::integral_constants with as_typelist, and
    4. Flatten that into the final list using typelist_cat.

    In step (1) we get the typelist sizes, so we need another typelist algorithm called typelist_size that fetches the size of type typelist:

    template<typename...List>
    struct typelist_size<typelist<List...> >
      : std::integral_constant<std::size_t, sizeof...(List)>
    {};
    

    We’re going to want to pass this to meta_compose, but typelist_size is a template, and meta_compose is expecting a Metafunction Class. We can write a wrapper:

    struct typelist_size_wrapper
    {
        template<typename List>
        using apply = typelist_size<List>;
    };
    

    Writing these wrappers is quickly going to get tedious. But we don’t have to. Below is a simple utility for turning a boring old metafunction into a Metafunction Class:

    template<template<class...> class F>
    struct meta_quote
    {
        template<typename...Ts>
        using apply = F<Ts...>;
    };
    

    The name quote comes from LISP via Boost.MPL. With meta_quote we can turn the typelist_size template into a Metafunction Class with meta_quote<typelist_size>. Now we can pass it to either meta_compose or typelist_transform.

    Our steps call for composing three metafunctions. It will look something like this:

    meta_compose<
        meta_quote<as_typelist_t>,            // Step 3
        meta_quote<std::make_index_sequence>, // Step 2
        meta_quote<typelist_size_t> >         // Step 1
    

    As I already mentioned, std::make_index_sequence takes an integer not a type, so it can’t be passed to meta_quote. This is a bummer. We can work around the problem with a variant of meta_quote that handles those kinds of templates. Let’s call it meta_quote_i:

    template<typename Int, template<Int...> class F>
    struct meta_quote_i
    {
        template<typename...Ts>
        using apply = F<Ts::value...>;
    };
    

    With meta_quote_i, we can compose the three functions with:

    meta_compose<
        meta_quote<as_typelist_t>,              // Step 3
        meta_quote_i<std::size_t,
                     std::make_index_sequence>, // Step 2
        meta_quote<typelist_size_t> >           // Step 1
    

    Now we can pass the composed function to typelist_transform:

    typelist_transform_t<
        typelist<as_typelist_t<Tuples>...>,
        meta_compose<
            meta_quote<as_typelist_t>,
            meta_quote_i<std::size_t, make_index_sequence>,
            meta_quote<typelist_size_t> > > >;
    

    Voila! We have turned our lists of tuples into the list of lists: [[0,1,2],[],[0,1,2],[1,2]]. To get the final result, we smoosh this into one list using typelist_cat:

    // E.g. [0,1,2,0,1,2,0,1]
    typelist_cat_t<
        typelist_transform_t<
            typelist<as_typelist_t<Tuples>...>,
            meta_compose<
                meta_quote<as_typelist_t>,
                meta_quote_i<std::size_t, make_index_sequence>,
                meta_quote<typelist_size_t> > > >;
    

    The result is the K indices that we pass to the tuple_cat_ helper. And to repeat from above, the I indices are computed with:

    // E.g. [0,0,0,2,2,2,3,3]
    typelist_cat_t<
        typelist_transform_t<
            typelist<as_typelist_t<Tuples>...>,
            typelist_transform_t<
                as_typelist_t<make_index_sequence<N> >,
                meta_quote<meta_always> >,
            meta_quote<typelist_transform_t> > >;
    

    I won’t step through it, but I’ll draw your attention to two things: on line (7) we make use of a strange type called meta_always (described below), and on line (8) we pass typelist_transform as the function argument to another call of typelist_transform. Talk about composability!

    So what is meta_always? Simply, it’s a Metafunction Class that always evaluates to the same type. Its implementation couldn’t be siimpler:

    template<typename T>
    struct meta_always
    {
        template<typename...>
        using apply = T;
    };
    

    I’ll leave you guys to puzzle out why the above code works.

    Summary

    I set out trying to find a minimal useful set of primitives for manipulating lists of types that would be fit for standardization. I’m happy with the result. What I’ve found is that in addition to the typelist template, we need a small set of algorithms like the ones needed to implement tuple_cat:

    • typelist_apply
    • typelist_size
    • typelist_transform
    • typelist_cat
    • as_typelist

    Some other typelist algorithms come up in other metaprogramming tasks:

    • make_typelist (from a count and type)
    • typelist_push_front
    • typelist_push_back
    • typelist_element (indexing into a typelist)
    • typelist_find and typelist_find_if
    • typelist_foldl (aka, accumulate) and typelist_foldr
    • etc.

    In addition, for the sake of higher-order metafunctions like typelist_transform and typelist_find_if, it’s helpful to have a notion of a Metafunction Class: an ordinary class type that can be used as a metafunction. A small set of utilities for creating and manipulating Metafunction Classes is essential for the typelist algorithms to be usable:

    • meta_apply
    • meta_quote
    • meta_quote_i
    • meta_compose
    • meta_always

    For other problems, the ability to partially apply (aka bind) Metafunction Classes comes in very handy:

    • meta_bind_front
    • meta_bind_back

    And that’s it, really. In my opinion, those utilities would meet the needs of 95% of all metaprograms. They are simple, orthogonal, and compose in powerful ways. Since we restricted ourselves to the typelist data structure, we ended up with a design that is vastly simpler than Boost.MPL. No iterators needed here, which makes sense since iterators are a pretty stateful, iterative abstraction, and metaprogramming is purely functional.

    One Last Thing…

    Below is one more metafunction to tickle your noodle. It’s an N-way variant of transform: it takes a list of typelists and a Metafunction Class, and builds a new typelist by mapping over all of them. I’m not suggesting this is important or useful enough to be in the standard. I’m only showing it because it demonstrates how well these primitive operations compose to build richer functionality.

    // ([[a,b,c],[x,y,z]], F) -> [F(a,x),F(b,y),F(c,z)]
    template<typename ListOfLists, typename Fun>
    struct typelist_transform_nary :
      typelist_transform<
        typelist_foldl_t<
          ListOfLists,
          make_typelist<
            typelist_front_t<ListOfLists>::size(),
            Fun>,
          meta_bind_back<
            meta_quote<typelist_transform_t>,
            meta_quote<meta_bind_front> > >,
        meta_quote<meta_apply> >
    {};
    

    Enjoy!

    Update: This comment by tkamin helped me realize that the above typelist_transform_nary is really just the zipWith algorithm from the functional programming world. I’ve renamed it in my latest code, and provided a typelist_zip metafunction that dispatches to typelist_zip_with with meta_quote<typelist> as the function argument. Very nice!

    "\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.

  • Customization Point Design in C++11 and Beyond

    (Disclaimer: here be esoteric language wonkery. Abandon all hope.)

    If you read or write Generic-code-with-a-capitol-‘G’, you may have written or seen code like this:

    using std::swap;
    swap( a, b );
    

    The first line brings std::swap into consideration, and the second makes an unqualified call to the swap function. I call this the “Std Swap Two-Step”.

    Why do we do the Two-Step? It has to do with the decidedly wonky way C++ resolves function calls in templates. I won’t fully elaborate on two-phase name lookup (you’re welcome), but suffice it to say that we do it for the sake of genericity: We make an unqualified call to swap in order to find an overload that might be defined in a and b‘s associated namespaces (itself a rich topic), and we do using std::swap so that, on the off-chance that there is no such overload, we find the default version defined in the std namespace.

    We call swap and functions like it customization points — hooks used by generic code that end-users can specialize to customize the behavior for their types.

    Are there other standard customization points? You bet. When you use a range-based for loop, the compiler inserts calls to unqualified begin and end to get the bounds of the range. So begin and end are customization points. Depending on how you read the specification of std::reverse, iter_swap may also be a customization point. (I think it is, or that it should be.) And other customization points may be in the offing. Proposal N4155, proposes non-member size for fetching the size of a range, and my own N4128 will propose size as a customization point as well.

    Trouble With The Two-Step

    Have you seen code that makes qualified calls to swap in a template, like std::swap( a, b ); ? Congratulation, you have probably found a bug. If the type of a and b overloads swap in its own namespace, a qualified call to std::swap won’t find it. It’s an all-too-easy mistake to make.

    The problem with the Two-Step is that is forces users to type more to do the right thing. FAIL. Most damning, it requires users to either blindly memorize and regurgitate the Two-Step pattern, or worse: understand two-phase name lookup in templates.

    Through With The Two-Step

    We need a better solution for the design of customization points in C++. In my own range library, I gave a great deal of thought to the problem, and I think I have an answer. Below is how I would like to see a future version of the Standard Library define std::begin, to pick an example at random. I explain it after the break:

    namespace std
    {
      namespace __detail
      {
        // define begin for arrays
        template<class T, size_t N>
        constexpr T* begin(T (&a)[N]) noexcept
        {
          return a;
        }
    
        // Define begin for containers
        // (trailing return type needed for SFINAE)
        template<class _RangeLike>
        constexpr auto begin(_RangeLike && rng) ->
          decltype(forward<_RangeLike>(rng).begin())
        {
          return forward<_RangeLike>(rng).begin();
        }
    
        struct __begin_fn
        {
          template<class R>
          constexpr auto operator()(R && rng) const ->
            decltype(begin(forward<R>(rng)))
          {
            return begin(forward<R>(rng));
          }
        };
      }
    
      // To avoid ODR violations:
      template<class T>
      struct __static_const
      {
        static constexpr T value{};
      };
    
      template<class T>
      constexpr T __static_const<T>::value;
    
      // std::begin is a global function object!
      namespace
      {
        constexpr auto const & begin =
            __static_const<__detail::__begin_fn>::value;
      }
    }
    

    Let’s break this down. First, we define a couple of begin free functions in a std::__detail namespace. These overloads handle array types and range-like things with .begin() member functions. (Think of the standard containers.)

    Next, we define a __begin_fn class with an overloaded function call operator in the std::__detail namespace that returns the result of making an unqualified call to begin. At this point in the source code, the name begin refers to a function overload set.

    Finally, we define a std::begin object of type std::__detail::__begin_fn in a round-about sort of way, the details of which are not too relevant. The important bit is that std::begin is a function object.

    Implementers of range-like types can hook this customization point the same way they always have: by defining a begin free function in their type’s associated namespace. See below:

    namespace NS {
      struct S {};
      int * begin( S & s );
    }
    
    int main() {
      NS::S s;
      int *p = std::begin(s); // calls NS::begin(s)
    }
    

    Function Objects and Customization Points

    Argument-dependent lookup and customization points are a match made in heaven. But argument-dependent lookup is only done for free functions, and my std::begin is a function object. Argument-dependent lookup isn’t done for function objects. What’s going on?

    The short answer is that the std::begin function object is doing the Two-Step so that you don’t have to. If std::begin were defined this way, you could just make qualified calls to std::begin and the right thing would happen. You could also do the Two-Step, bringing std::begin into scope with a using declaration, and calling it unqualified, and get the same behavior. Either way, if there is a begin free function defined in the argument’s associated namespace, it will get used.

    A subtle but important point is that, if you do the Two-Step, the call is still routed through the std::begin function object. I mean that in the code below:

    using std::begin;
    begin( v );
    

    …if std::begin were an object instead of a function, then what looks like an unqualified function call is not; it’s a call to std::__detail::__begin_fn‘s overloaded function call operator. Think of this as the Generic equivalent of the Gang of Four‘s Template method pattern:

    In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure. This use of “template” is unrelated to C++ templates.
    — Wikipedia

    In this case, the “algorithm” is std::begin, and the certain steps that users can redefine is begin. What’s the point, you ask? We can do extra parameter checking in std::begin. Read on.

    Customization Points and Concepts Lite

    Customization points are scary in a way. In today’s language, if you define a free function called swap, it better do what the Standard Library expects swap to do. Otherwise, all hell breaks loose in the standard algorithms. Likewise, you can shoot yourself if you define a begin or end free function that doesn’t return iterators. So the Standard Library has laid claim to those names globally. That’s why customization points are such a concern for the standardization committee; the more we add, the more names we reserve globally, and the bigger the potential problem gets for the users.

    Enter Concepts Lite. With Concepts Lite, we can constrain our customization points to only work with the types that model certain concepts. For instance, it should be an error to call std::begin on something that doesn’t look like a range, don’tcha think? With Concepts Lite and global function objects, we can have that. We can define std::__detail::__begin_fn like this:

    // A _RangeLike is something we can call begin(r)
    // and end(r) on:
    concept _RangeLike<class T> =
      requires(T t) {
        typename IteratorType<T>;
        { begin(t) } -> IteratorType<T>;
        { end(t) } -> IteratorType<T>;
        requires Iterator<IteratorType<T>>;
      };
    
      struct __begin_fn
      {
        // LOOK! R must be _RangeLike!
        template< _RangeLike R >
        constexpr auto operator()(R && rng) const ->
          decltype(begin(forward<R>(rng)))
        {
          return begin(forward<R>(rng));
        }
      };
    

    First we define the _RangeLike concept as something on which we can call begin and end, such that they both return iterators of the same type. (Or, if you agree with N4128, different types that are comparable.) Then we use the _RangeLike concept to constrain __begin_fn::operator() and by extension std::begin. Now std::begin won’t compile for things that aren’t sufficiently range-like, which makes it safer to lay claim to a common identifier like begin.

    If std::begin is a function object as opposed to a free function, it’s not easy to route around this concept checking. Code that does the Two-Step won’t accidentally hijack some unrelated begin function in some random namespace. It will always resolve to std::begin, which will politely reject invalid code.

    You don’t have to wait for Concepts Lite to reap the benefits, either. See my post on emulating Concepts Lite in C++11.

    Summary

    What’s all this mean? Simply:

    • Users could just call std::begin and it would do ADL for them.
    • std::begin(rng) wouldn’t compile unless:
      • it returns an iterator, and
      • std::end(rng) also compiles and returns an iterator of the same type.
    • Code that does using std::begin; begin(rng); isn’t going to dispatch to some random begin function unless the argument satisfies the constraints of std::begin.

    More generally, there is a design pattern that we can use to make safe and convenient customization points. If you’re writing a generic library with customization points, I recommend using this pattern.

    Addendum: An Ode to Global Function Objects

    We get an additional benefit from making std::begin a global function object:

    • You can pass std::begin as an argument to higher-order functions.

    That’s a benefit of function objects over free functions in general, and it’s why I generally prefer global function objects over free functions these days (except when I’m defining customization points). Defining global function objects is more work, but it has the nice effect of turning off argument-dependent lookup, which really only makes sense for operator overloads and customization points. First-order functions rule. ADL sucks (except in the few places where it’s awesome).

    Update

    A quick note about generic lambdas, since I’ve gotten questions. In C++14, we can define polymorphic function objects very concisely using generic lambdas. So can we use lambdas to define global function objects and save some typing, as below:

    // Better?
    constexpr auto begin = [](auto && rng) {
      using __detail::begin;
      return begin(forward<decltype(rng)>(rng));
    };
    

    The answer, sadly, is no for a host of reasons:

    1. Lambdas do not have constexpr constructors.
    2. I don’t know how to solve the ODR problem for lambdas. If std::begin were defined this way, then each translation unit would see different std::begin objects at different addresses. In theory, that could cause problems.
    3. I don’t know how to constrain a generic lambda.
    4. With automatic return type deduction, invalid calls to begin cause a hard error rather than being SFINAE’ed away. That might not be a huge problem for std::begin, but it most certainly is a huge problem for std::__detail::begin. The begin overloads found by ADL must use SFINAE (or concept checks); otherwise, you would end up trying to call .begin() on some object that doesn’t have a .begin() member function.

    In short, even in C++14, I think we need the ugly hackery I show. Maybe C++17 will bring relief.

    "\e"

    "\e"

  • N4128: Ranges for the Standard Library

    Eleven months ago, I began work on an updated range library for modern C++. Yesterday, I submitted a proposal to the C++ standardization committee to add ranges to the Standard Library. The proposal presents a vision for a future Standard Library that is familiar and yet more powerful, more usable, and more efficient than today’s.

    My goal is nothing less than to change how C++ programmers write code. Seriously.

    I want more people to use the standard algorithms. I want it to be simple to do so. I want operations on data to compose in logical, simple, succinct and powerful ways. I want it to be easy for people to adapt their data so that those operations can be applied to them. I want it to be easy to create new operations that compose: lazy algorithms that snap together like Lego blocks and that give your programs a literate, declarative feel. I want it to be efficient. And it has to be safe.

    D4128 lays the foundation. I’m honored to list Sean Parent and Andrew Sutton as coauthors. Although most of the text of the proposal is mine, many of the ideas in it are not.

    Next month I fly to Urbana to present our work to the committee. Come to Urbana and watch the fun. And wish me luck.

  • 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"
  • Assert and Constexpr in C++11

    Here’s a simple question: in C++11 what’s the best way to put debug checks in constexpr functions? Since assert is not constexpr, the obvious doesn’t work:

    constexpr bool in_range(int val, int min, int max)
    {
        assert(min <= max); // OOPS, not constexpr
        return min <= val && val <= max;
    }
    

    In C++14 this is OK, but in code that must be portable to C++11 it’s not. This is a known problem, and the recommended solution is to use a throw expression on failure. This totally non-obvious solution has the neat effect of causing a compile-time error when the arguments are known at compile-time:

    constexpr bool in_range(int val, int min, int max)
    {
        return (min <= max)
          ? min <= val && val <= max
          : throw std::logic_error("Assertion failed!");
    }
    
    constexpr bool res1 = in_range(4, 1, 5); // OK
    constexpr bool res2 = in_range(4, 5, 1); // Compile error!
    
    int min = 1, max = 5;
    bool b = in_range( 4, max, min ); // Exception!
    

    That’s fine except for one thing: it turns runtime assertions — which should be unrecoverable — into “recoverable” runtime exceptions. That’s really, really bad. Assertions are used to detect logic errors in your program. If one fires, it means your your program state is suspect. There is no way to safely recover from an invalid program state, so an exception is the wrong tool for the job.

    Let’s look at a couple of solutions:

    Fix #1: noexcept

    One fix is pretty simple: add noexcept to the constexpr function:

    constexpr
    bool in_range(int val, int min, int max) noexcept
    {
        return (min <= max)
          ? min <= val && val <= max
          : throw std::logic_error("Assertion failed!");
    }
    
    int min = 1, max = 5;
    bool b = in_range( 4, max, min ); // Terminate!
    

    Notice that in_range is declared noexcept — but it throws on error! What happens when a propagating exception hits a noexcept? It’s game over, man. The runtime calls std::terminate, which shuts the process down. That’s what an assert is supposed to do.

    Fix #2: std::quick_exit

    Here’s another simple fix: We could define a assert_failure exception type that shuts the process down in its constructor:

    struct assert_failure
    {
        explicit assert_failure(const char *sz)
        {
            std::fprintf(stderr, "Assertion failure: %s\n", sz);
            std::quick_exit(EXIT_FAILURE);
        }
    };
    

    Now, we can use assert_failure in our constexpr functions to catch bugs as follows:

    constexpr bool in_range(int val, int min, int max)
    {
        return (min <= max)
          ? min <= val && val <= max
          : throw assert_failure("min > max!");
    }
    

    Notice how the assert_failure constructor reports the error and then calls std::quick_exit. quick_exit is a new function in C++11 that pretty much just shuts the process down without calling any destructors for locals or global objects. That’s almost certainly what you want. If your program state is borked, executing a pile of arbitrary code is a bad idea. It could do more harm than good. Any code that absolutely must execute on termination no matter what should be registered with std::at_quick_exit. You should limit that to things like saving user edits into a look-aside for attempted recovery later. (But don’t corrupt known-good data!)

    Fix #3: assert

    The trouble with Fix #2 is that it interferes with debuggers, which know about assert and what to do when one fires. The third fix is to just use assert, but to do it in a sneaky way. Once again, we define an assert_failure type, but this time pass to the constructor a function that does the assert for us:

    struct assert_failure
    {
        template<typename Fun>
        explicit assert_failure(Fun fun)
        {
            fun();
            // For good measure:
            std::quick_exit(EXIT_FAILURE);
        }
    };
    
    constexpr bool in_range(int val, int min, int max)
    {
        return (min <= max)
          ? min <= val && val <= max
          : throw assert_failure(
              []{assert(!"input not in range");}
            );
    }
    

    Now on runtime failures, we get the assert we really wanted in the first place:

    assertion "!"input not in range"" failed: file "main.cpp",
    line 41, function: auto in_range(int, int, int)::(anonymou
    s class)::operator()() const
    Aborted (core dumped)
    

    Summary

    If you want to add debug checks your C++11 constexpr functions, throw and noexcept are your friends. Alternately, you can define an assert_failure exception type that makes no bones about shutting your process down RIGHT NOW, either with std::quick_exit or with the trusty ol’ assert macro.

    "\e"
    "\e"
  • Cpp-Next.Com and the Expressive C++ Series

    The C++ community is suffering from the loss of the cpp-next.com website and all the great content that was once hosted there. In the past 2 months, I’ve gotten many questions both about the site and about the fate of my “Expressive C++” article series. In response, I will re-post my old articles on this blog. But I’m busy and it’ll take time. In the meanwhile, if you have a desperate need for a readable introduction to Boost.Proto and domain-specific embedded languages in C++, and you don’t mind reading raw markdown, email me. I’ll send you what I have.

  • Range Comprehensions

    I’ve been busy since I last wrote about ranges. I have a lot of news to share, but in this post, I’m going to narrowly focus on a recent development that has me very excited. It’s a new feature that I’m calling range comprehensions, and they promise to greatly simplify the business of creating custom ranges.

    List Comprehensions

    If you’re familiar with list comprehensions from Haskell or Python, your ears might have pricked up when I said “range comprehensions.” List comprehensions give you a pithy way to generate new lists from existing ones, either by transforming thenm, filtering them, or combining them, or whatever. Here, for instance, is a Haskell program for generating the first 10 Pythagorean triples:

    main = print (take 10 triples)
    
    triples = [(x, y, z) | z <- [1..]
                         , x <- [1..z]
                         , y <- [x..z]
                         , x^2 + y^2 == z^2]
    

    The way to read the triples line is this: generate a list of tuples (x, y, z) where z goes from 1 to infinity, x goes from 1 to z (inclusive), and y goes from x to z, but only yield those triples for which x^2 + y^2 == z^2 is true. The code then generates every combination of x, y, and z in the specified ranges in some order and filters it, yielding a list of the Pythagorean triples. Beautiful. Of particular interest is the fact that, since Haskell is lazy, there is no problem with a comprehension that generates an infinite list.

    Back-Story

    Back in October, I published a blog post about API design and std::getline in which I showed how a range-based interface is better than the existing one. My friend Bartosz Milewski commented that ranges are difficult to work with and challenged me to show the range-based equivalent of the above pithy Haskell program. I admit that at the time, I had no answer for Bartosz.

    Recently, Bartosz published a blog post about just this problem. In his post, Bartosz describes some pretty simple results from category theory (if any category theory can be described as “simple”), and applies it to the problem of generating the Pythagorean triples lazily in C++. It’s a great post, and you should read it. Here, finally, was my answer. Although Bartosz’s code was terribly inefficient, somewhat difficult to reason about, and not formulated in terms of STL-ish concepts, I knew the direction I had to take.

    Introducing Range Comprehensions

    Without further ado, here is my solution to the Pythagorean triples problem:

    using namespace ranges;
    
    // Lazy ranges for generating integer sequences
    auto const intsFrom = view::iota;
    auto const ints = [=](int i, int j)
        {
            return view::take(intsFrom(i), j-i+1);
        };
    
    // Define an infinite range of all the Pythagorean
    // triples:
    auto triples =
        view::for_each(intsFrom(1), [](int z)
        {
            return view::for_each(ints(1, z), [=](int x)
            {
                return view::for_each(ints(x, z), [=](int y)
                {
                    return yield_if(x*x + y*y == z*z,
                        std::make_tuple(x, y, z));
                });
            });
        });
    
    // Display the first 10 triples
    for(auto triple : triples | view::take(10))
    {
        std::cout << '('
            << std::get<0>(triple) << ','
            << std::get<1>(triple) << ','
            << std::get<2>(triple) << ')' << '\n';
    }
    

    Lines 4 and 5 define intsFrom and ints, which are lazy ranges for generating sequences of integers. Things don’t get interesting until line 12 with the definition of triples. That’s the range comprehension. It uses view::for_each and yield_if to define a lazy range of all the Pythagorean triples.

    view::for_each

    What is view::for_each? Like std::for_each, it takes a range and function that operates on each element in that range. But view::for_each is lazy. It returns another range. The function that you pass to view::for_each must also return a range. Confused yet?

    So many ranges, but what’s going on? Conceptually, it’s not that hard. Let’s say that you call view::for_each with the range {1,2,3} and a function f(x) that returns the range {x,x*x}. Then the resulting range will consist of the elements: {1,1,2,4,3,9}. See the pattern? The ranges returned by f all got flattened. Really, range flattening is all that’s going on.

    Now look again at line 12 above:

    auto triples =
        view::for_each(intsFrom(1), [](int z)
        {
            return view::for_each(ints(1, z), [=](int x)
            {
                return view::for_each(ints(x, z), [=](int y)
                {
                    return yield_if(x*x + y*y == z*z,
                        std::make_tuple(x, y, z));
                });
            });
        });
    

    For every integer z in the range 1 to infinity, we call view::for_each (which, recall, returns a flattened range). The inner view::for_each operates on all the integers x from 1 to z and invokes a lambda that captures z by value. That function returns the result of a third invocation of view::for_each. That innermost lambda, which finally has x, y, z, makes a call to a mysterious-looking function that is provocatively named yield_if. What’s that?

    yield_if

    The semantics of yield_if is to “inject” the tuple (x,y,z) into the resulting sequence, but only if is a Pythagorean triple. Sounds tricky, but it’s really very simple. Recall that the function passed to view::for_each must return a range. Therefore, yield_if must return a range. If the condition x*x + y*y == z*z is false, it returns an empty range. If it’s true, it returns a range with one element: (x,y,z). Like I said, simple. There’s also a function called yield that unconditionally returns a single-element range.

    Now that you know how it works, you can forget it. You can just use view::for_each and yield_if as if you were writing a stateful function that suspends itself when you call yield or yield_if, kind of like a coroutine. After all, I picked the name “yield” to evoke the yield keyword from C#. That keyword gives the function it appears in precisely those coroutine-ish semantics. What’s more, C# functions that have yield statements automatically implement C#’s IEnumerable interface. IEnumerable fills the same niche as the Iterable concept I’ve described in previous posts. That is, you can loop over the elements.

    For instance, in C# you can do this (taken from Wikipedia):

    // Method that takes an iterable input (possibly an
    //  array) and returns all even numbers.
    public static IEnumerable<int>
    GetEven(IEnumerable<int> numbers) {
        foreach(int i in numbers) {
            if((i % 2) == 0) {
                yield return i;
            }
        }
    }
    

    With range comprehensions, equivalent code looks like this:

    auto GetEvens =
        view::for_each(numbers, [](int i)
        {
            return yield_if((i % 2) == 0, i);
        });
    

    That’s darn near the same thing, and we don’t need any special keyword or compiler magic.

    Performance

    Ranges that return ranges that return ranges, oy vey. How horribly does it perform at runtime? As it turns out, not horribly at all, but a lot depends on how good your optimizer is.

    I wrote a simple benchmark program that iterates over the first 3000 triples and does some trivial computation with them. I do this in two ways. One is with the range comprehension above, and the other is with this triply-nested for loop:

    for(int z = 1;; ++z)
    {
        for(int x = 1; x <= z; ++x)
        {
            for(int y = x; y <= z; ++y)
            {
                if(x*x + y*y == z*z)
                {
                    result += (x + y + z);
                    ++found;
                    if(found == 3000)
                        goto done;
                }
            }
        }
    }
    done:    
    

    You would expect this solution to fly and the range-based one to crawl. But here are the numbers using a hot-off-the-presses gcc-4.9 with -O3:

    Raw loop:             2.2s
    Range comprehension:  2.3s
    

    That’s it?! Yes, all that extra work being done by the range comprehension is totally transparent to the optimizer, which generates near-optimal code. Kind of amazing, isn’t it?

    If, however, your compiler of choice is clang, I have some bad news for you. The range comprehension is (wait for it) 15 times slower. Dear god, that’s awful. I guess that goes to show that despite the astounding awesome-ness of clang in most respects, its optimizer still has some ways to go.

    Summary

    Haskell and Python have list comprehensions. C# has LINQ and yield. And now C++ has range comprehensions. It’s now pretty trivial to generate non-trivial sequences on the fly, lazily and efficiently, in a way that plays well with all the STL algorithms. Like I said, I’m pretty excited.

    Acknowledgements

    My deep thanks to Bartosz Milewski for getting me 90% of the way there. I couldn’t have done this without his insights, and the insights of all the functional programmers and category theoreticians that came before. Math FTW!

    "\e"
    "\e"
    "\e"