Author: Eric Niebler

  • Range Concepts, Part 4 of 4: To Infinity And Beyond

    Last time, I introduced a new concept, Iterable, and showed how it solved many of the problems with pair-of-iterator-style ranges. This time around, I’m going to extend Iterable in small ways to make programming with infinite ranges safer and more efficient. Disclaimer: The ideas in this post are more speculative than in the previous three. I’m looking forward to the discussion.

    Quick Recap

    Previously I described the problems that crop up when representing infinite and delimited ranges with pairs of iterators, the first three of which are:

    1. Iteration is slow
    2. The ranges are forced to model a weaker concept than they could otherwise
    3. Their implementations are awkward

    My solution to that problem is the Iterable concept; that is, to allow the end of the range to have a different type than the beginning of the range. Once you allow that:

    1. Performance is improved because sentinel-ness is encoded in the C++ type system and so doesn’t need to be check at runtime.
    2. The concept a range can model is no longer limited by the concept that can be modeled by the sentinel, which by its very definition cannot be decremented or dereferenced.
    3. Since sentinel-ness is now a compile-time property and does not need to be explicitly checked, the logic of iterator comparisons is simpler.

    There were two more issues that crop up with infinite ranges in particular. They are:

    1. Some STL algorithm just don’t work with infinite ranges
    2. Infinite or possibly-infinite ranges will overflow their difference_type

    These are the issues I’ll focus on in this post.

    Infinite Iterables

    iota_range is an infinite ranges of integers, starting at some value and counting up, forever. (Suppose that iota_range uses an infinite-precision integer type, so it really never ends.) It is a sorted forward range. Binary search algorithms work with sorted forward ranges, so they should work with iota_range, right? Wrong! You can’t conquer infinity by dividing it. (You can quote me on that.)

    Can we make the standard algorithms safer, so the algorithms that don’t work with infinite ranges fail to compile if you pass them one? In the current formulation of the STL the answer is no. There’s no way, given two iterators of the same type, to tell at compile time if they denote an infinite range. Think about it for a minute: the following is perfectly ok, and guaranteed to finish:

    // OK, this finishes quickly
    iota_range<bigint> rng;
    auto i = std::lower_bound(rng.begin(),
                              std::next(rng.begin(), 10),
                              5);
    

    But the following will run forever:

    // Oops! this runs forever. :'-(
    iota_range<bigint> rng;
    auto i = std::lower_bound(rng.begin(),
                              rng.end(),
                              5);
    

    If rng.begin() is the same type as rng.end(), those two calls resolve to the same instantiation of lower_bound. There’s no way for lower_bound to tell whether it’s going to run forever or not. But if we allow the sentinel type to be different, it opens the door to greater compile-time checking. How? Suppose we had a type function (aka a metafunction) called DenotesInfiniteSequence that takes a type pair (BeginType, EndType) and says whether the sequence is infinite or not. We’ve already established that if BeginType and EndType are the same, DenotesInfiniteSequence has to always return false since it can’t know. But if they’re different — say, if EndType is a special type called unreachable_sentinel or something — then we can know at compile-time that the sequence is infinite.

    So the Iterable concept naturally give us a way to test for infinite ranges, right? Well…

    Infinite Ranges

    Some ranges might genuinely be infinite even though their begin and end iterators have the same type. We want to catch those, too. Consider:

    // An infinite range of zeros
    class zeros : public range_facade<zeros>
    {
        friend range_core_access;
        struct impl
        {
            bool sentinel;
            int current() const { return 0; }
            void next() {}
            bool equal(impl that) const
            { return sentinel == that.sentinel; }
        };
        // begin() and end() are implemented by range_facade
        // in terms of begin_impl and end_impl. They will 
        // have the same type.
        impl begin_impl() const { return {false}; }
        impl end_impl() const { return {true}; }
    };
    // zeros models the Range concept
    CONCEPT_ASSERT(Range<zeros>());
    
    int main()
    {
        // Oops! This will run forever.
        for_each(zeros(), [](int i) {/*...*/});
    }
    

    We’d like to be able to catch mistakes like this if it’s possible, but clearly, the binary DenotesInfiniteSequence type function we hypothesized above isn’t up to the task. For zeros, the types BeginType and EndType are the same, so DenotesInfiniteSequence would return false. And yet zeros is infinite.

    So instead of a DenotesInfiniteSequence type function that takes a (BeginType,EndType) pair, let’s have a unary IsInfinite type function that takes a range type. What could be simpler? In code, it would be a type trait:

    // Report whether an Iterable is infinite or not
    template<typename Iterable>
    struct is_infinite
      : std::integral_constant<bool, true-or-false>
    {};
    

    This type trait can be used to define a concept FiniteIterable as follows:

    // Current proposed Concept Lite syntax
    template<typename T>
    concept bool FiniteIterable =
        Iterable<T> && !is_infinite<T>::value;
    

    (Why FiniteIterable instead of InfiniteIterable? I’ll say why in a minute.) Every FiniteIterable is an Iterable. In fact, there’s a parallel refinement hierarchy here, just as there is with Ranges:

    Finite Iterable Concept Hierarchy

    Finite Iterable Concept Hierarchy

    And as with Range, we don’t actually need to define all these concepts in code. “Finite-ness” is orthogonal to the Iterable concept hierarchy and can be queried separately.

    So why FiniteIterable instead of InfiniteIterable? It comes down to the algorithms and their requirements. There are no algorithms that require that their range arguments be infinite. So being able to say requires InfiniteIterable<T> is useless. But an algorithm like lower_bound would very much like to require that the range it’s operating on has a definite end; hence FiniteIterable.

    Now, all iterable things model FiniteIterable by default, and a type has to opt in to being infinite. How? One way is to specialize is_infinite. As a convenience, the utilities for building iterables and ranges take an optional IsInfinite template parameter, so opting in is easy. Here’s how zeros looks now:

    // An infinite range of zeros
    class zeros : public range_facade<zeros, true>
    {   // ... IsInfinite ...................^^^^
        // ... as before ...
    };
    // zeros is a Range but it's not Finite
    CONCEPT_ASSERT(Range<zeros>());
    CONCEPT_ASSERT(!FiniteIterable<zeros>());
    

    With the addition of the FiniteIterable concept, the algorithms that require finite-ness have an easy way to check for it at compile-time. This is only possible with a range-based interface, so we can add that to the long list of advantages ranges have over iterators.

    Possibly Infinite Ranges

    Once we have a way to separate the finite ranges from the infinite, we now have to categorize the ranges. This should be simple; either a range is finite or it’s not, right? It’s actually trickier than that. Take an istream range, for instance. It might be infinite, or it might not. You don’t know. Most of the time, the stream runs dry eventually and the iteration stops. In fact, almost all the time. But sometimes…

    This is a sticky situation. Should we be prevented from passing an istream range to an algorithm just because it might go on forever? I think the answer is yes, but I confess I haven’t made up my mind about that yet. I think we need more real-world usage.

    Counting the Uncountable

    With infinite ranges, we run into an inherent difficulty: all iterators — and by extension, all iterables — have an associated difference_type. Alex Stepanov has this to say about an iterator’s difference_type:

    DistanceType returns an integer type large enough to measure any sequence of applications of successor allowable for the type. 1

    Since an iterator over an infinite sequence permits an infinite number of applications of successor, we need an integer type large enough … well, infinitely large. Does this problem have a solution? As in the words of Tevye from Fiddler on the Roof, “I’ll tell you…. I don’t know.”

    No flash of insight has been forthcoming. Instead, here’s a core dump of my brain on the issue:

    1. C++ needs bigint, an infinite-precision integral type. Other languages have it. C++ is a great language for building libraries, and this is crying out for a library solution. If such a type existed, an infinite range might choose that as its difference_type. That would come with a not-insignificant performance hit.
    2. Infinite ranges could use safe_int as its difference_type. safe_int behaves like an int, but it can represent infinity. Instead of overflowing and going into undefined-behavior-land, a safe_int clips to infinity and stays there. The two biggest problems with letting an iterator’s difference_type overflow are undefined behavior and the inability to tell after the fact if anything went wrong. With safe_int, you can avoid the UB and have a way to tell at runtime if something bad happened. That might be enough in some situations. If this feels like a Big Hack to you, that’s because it is.
    3. An alternate design of safe_int might be to throw an exception on overflow rather than clip to infinity. That might be appropriate in some situations.
    4. Another approach is to look at where the library uses difference_type and give users a way to specify that a different type be used. For instance, the API of a range-based distance algorithm might take a range and optionally a starting count. It would default to difference_type{0}, but if you passed in, say, a bigint then you’re opting in to safer, slower code.
    5. You can ignore the problem. Users that worry about overflow can use a counted range adaptor to make sure iteration stops before the difference_type overflows.
    6. Something else I haven’t thought of.

    Here’s my opinion: I don’t like anything that introduces unnecessary runtime overhead, so std::ptrdiff_t is an acceptable default for difference_type. In addition, we should design range-based interfaces in such a way as to give users a way to specify a different difference_type when overflow is a concern. So basically, I’m going with options (4) and (5). The other library types — bigint and maybe a policy-based safe_int — would be nice-to-haves that users could pass to these algorithms to get the safety/speed tradeoff that makes sense for them.

    That’s the best I’ve got.

    Summary, and Next Steps

    Maybe after the first 3 posts about range concepts you were feeling good, like it’s all falling into place, and now you’re kind of confused. But I think we’re in a good place, much better than we were. I described 5 problems with pair-of-iterator ranges. A new concept — Iterable — addresses 3 of them very well (slow iteration, modeling weaker-than-necessary concepts, awkward implementations). The 4th problem (infinite ranges) we can address with a further refinement of Iterable. And we have some options for dealing with the 5th (overflow), which is helped by being able to tell the infinite ranges apart from the finite ones. So the new concepts help there too. I think this is a promising start.

    Some of you have asked if I’m planning to take these ideas to the C++ standardization committee. Indeed, I am. When we get language support for concepts (not if, when), there is very likely to be a push for a new, concept-ified version of the STL, probably in a different namespace. This wholesale rewrite is a prime opportunity for getting something like Iterable baked into the STL from day one.

    My next step is to start a discussion on the SG9 (Ranges) mailing list. It’s likely to be contentious, and I expect these ideas will evolve. Consider subscribing to the list and joining the discussion.

    Addendum

    Sean Parent has commented on my blog and made an interesting point about the importance of counted algorithms (e.g. copy_n). He’s challenged me to find a more efficient way of supporting counted ranges than my proposed solution. I have some initial thoughts on the issue that I’ll write up and publish here provided they pan out. At any rate, it’s clear that it’s time for brains other than mine to be working on this problem. C++17 is closer than you might think, and time’s a’wasting!

    x

    1. Stepanov, A; McJones, P. Elements of Programming. Addison-Wesley. 2009.↩

  • Range Concepts, Part 3 of 4: Introducing Iterables

    In the last two blog posts, I describes the challenges I’ve encountered while building a next-generation range library. In this post, I’ll sketch for you my proposed solution: refinements of the range concepts that allow delimited, infinite, and pair-o’-iterator-style ranges to fit comfortably within the concept hierarchy without loss of performance or expressive power and with increased safety. I’ve built a range library around these concepts that subsumes and extends all of the C++98 STL algorithms and the Boost.Range adaptors, so I can say with confidence that these concepts lead to a useful and consistent generic range library.

    Recap

    At the end of my last post, I summed up the issues of pair-o’-iterators (PoI)-style ranges as follows:

    • Delimited and infinite ranges generate poor code
    • These range types are sometimes forced to model weaker concepts than they might otherwise
    • Use of infinite ranges with some algorithms is unsafe
    • Delimited and infinite ranges are harder to implement than they need to be
    • Ranges that are possibly infinite can overflow their difference_type

    The first issue is particularly hard to swallow, so it’s where I’ll focus my energy in this post.

    The Range Concept

    Before I go any further, let’s be a little more formal about what “range” means. The C++ standard uses the word “range” all over the place without formally defining it. But we can infer from the section [iterator.range] that a range is something on which you can call begin and end to get back a pair of iterators where the end is reachable from begin. In the language of the current “Concepts Lite” proposal, we can formalize the Range concept as follows:

    using std::begin;
    using std::end;
    
    template<typename T>
    using Iterator_type =
        decltype(begin(std::declval<T>()));
    
    template<typename T>
    concept bool Range =
        requires(T range) {
            { begin(range) } -> Iterator_type<T>;
            { end(range) }  -> Iterator_type<T>;
            requires Iterator<Iterator_type<T>>;
        };
    

    This basically says that you can call begin and end on a range and that you get back iterators. There are refinements of the Range concept (not shown) called InputRange, ForwardRange, etc. that merely require more of their iterators. The refinement hierarchy is shown below. It’s fairly straightforward. (The above syntax was given to me by Andrew Sutton, the author of the Concepts Lite proposal, shortly after the February 2014 standardization committee meeting, so it’s guaranteed fresh. He warns me that the syntax may yet change in the future.)

    Range Concept Hierarchy

    Range Concept Hierarchy

    These concepts are the foundation of the Boost.Range library.

    Problem 1: Poor Code Generation

    If you recall, to implement delimited and infinite ranges as a pair of iterators, the end iterator must be some sort of sentinel iterator. A sentinel represents a conceptual position rather than a physical one. You can still think of it as the last-plus-one position, the only difference is that you won’t know the physical position until you reach it. Since the sentinel has the same type as the iterator, it requires a runtime test to determine whether a given iterator is the sentinel or not. This leads to slow iterator comparisons and awkward range implementations.

    The Iterable Concept

    Think of the things you do with iterators. You increment them, you dereference them, and you compare them for equality, right? What can you do with a sentinel iterator? Not much. You can’t change its position since it represents a conceptual position, not a physical one. You can’t dereference them, because they always stand in for the last-plus-one position, which is not dereferencable. But you can compare it to an iterator. In other words, a sentinel is a very weak iterator.

    The trouble with delimited and infinite ranges comes from trying to make a sentinel iterator into a regular iterator. It just isn’t one, and making it so causes problems. So just let it be. In other words:

    Let range sentinels have different types than their ranges’ iterators.

    The Range concept requires the begin and end iterator have the same type. If I allow the types to differ, I’m talking about something weaker than Range: the Iterable concept. Iterables are just like Ranges except the begin and end types differ. Here’s the Iterable concept:

    template<typename T>
    using Sentinel_type =
        decltype(end(std::declval<T>()));
    
    template<typename T>
    concept bool Iterable =
        requires(T range) {
            { begin(range) } -> Iterator_type<T>;
            { end(range) }  -> Sentinel_type<T>;
            requires Iterator<Iterator_type<T>>;
            requires EqualityComparable<
                Iterator_type<T>, Sentinel_type<T>>;
        };
    
    template<typename T>
    concept bool Range =
        Iteratable<T> &&
        Same<Iterator_type<T>, Sentinel_type<T>>;
    

    All Ranges are Iterables trivially. That is, the Range concept refines Iterable by adding one additional constraint: that begin and end have the same type. In fact, the Iterable concept hierarchy parallels the Range hierarchy nicely:

    Iterable Concept Hierarchy

    Iterable Concept Hierarchy

    This is what the hierarchy looks like when considering Ranges, Iterables, and Iterators, but it’s not necessarily the way we would actually define these concepts in our code. Notice that “rangeyness” — that is, whether begin and end have the same type — is orthogonal to the strength of the begin iterator. When we want to require that a type model RandomAccessRange, we can say requires RandomAccessIterable<T> && Range<T> and do away with the other Range concepts entirely.

    The difference between, say, a BidirectionalIterable and a ForwardIterable is in the concept modeled by the Iterable’s begin iterator. If the EqualityComparable constraint in the Iterable concept gives you pause, read on. I justify it below.

    Iterables and the STL Algorithms

    “But wait,” you say. “No STL algorithms will work with Iterables because they expect begin and end to have the same type!” That’s sadly true. So I went through all the STL algorithm to see which could be re-implemented in terms of the weaker concept. Take std::find for example:

    template<class InputIterator, class Value>
    InputIterator
    find(InputIterator first, InputIterator last,
         Value const & value)
    {
        for (; first != last; ++first)
            if (*first == value)
                break;
        return first;
    }
    

    Today, std::find requires Ranges. But notice how this algorithm never tries to change the position of the end iterator. The find algorithm can very easily be changed to work with Iterables instead of Ranges:

    template<class InputIterator, class Sentinel, class Value>
    InputIterator
    find(InputIterator first, Sentinel last,
         Value const & value)
    {
        for (; first != last; ++first)
            if (*first == value)
                break;
        return first;
    }
    

    That’s it. The change is so minor, you might even have a hard time spotting it!

    So, which C++98 algorithms can be made to work with Iterables instead of Ranges? Nearly all of them, it turns out. In fact, it’s easier to list the ones that don’t work with Iterables. They are:

    • copy_backward
    • The heap algorithms (push_heap, pop_heap, make_heap, sort_heap)
    • inplace_merge
    • nth_element
    • partial_sort and partial_sort_copy
    • next_permutation and prev_permutation
    • random_shuffle
    • reverse and reverse_copy
    • sort and stable_sort
    • stable_partition

    For the 50 or so others, getting them to work with Iterables is mostly a mechanical source code transformation. By defining the Iterable concept such that Range refines it, any algorithm implemented in terms of Iterable automatically works with Ranges, which lets us reuse code. And that’s super important. There’s too much code written for iterators to think about picking an incompatible abstraction now.

    The Proof is in the Perf

    But what do we gain? Let’s revisit our old friend, the C-style null-terminated string. In a previous post, I defined a c_string_range class and found that iterating through the characters generated very bad code. Let’s try again, this time using my range_facade helper to build an Iterable instead of a Range. The code looks like this:

    using namespace ranges;
    struct c_string_iterable
      : range_facade<c_string_iterable>
    {
    private:
        friend range_core_access;
        char const *sz_;
        char const & current() const { return *sz_; }
        void next() { ++sz_; }
        bool done() const { return *sz_ == 0; }
        bool equal(c_string_iterable const &that) const
        { return sz_ == that.sz_; }
    public:
        c_string_iterable(char const *sz)
            : sz_(sz) {}
    };
    

    The first thing we notice is that this code is a lot simpler than the old c_string_range class. The range_facade helper does all the heavy lifting here. The iterator and the sentinel are all implemented in terms of the primitives shown. Gone is the awkward and complicated equality comparison. But how does it perform? To test it, I generated the optimized assembly for the following two functions, one which used the old c_string_range class, and one that uses the new c_string_iterable:

    // Range-based
    int range_strlen(
        c_string_range::iterator begin,
        c_string_range::iterator end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    
    // Iterable-based
    int iterable_strlen(
        range_iterator_t<c_string_iterable> begin,
        range_sentinel_t<c_string_iterable> end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    

    Even if you don’t know much about assembly code, the following should speak to you:

    Range-based strlen Iterable-based strlen
        pushl    %ebp
        movl    %esp, %ebp
        pushl    %esi
        leal    8(%ebp), %ecx
        movl    12(%ebp), %esi
        xorl    %eax, %eax
        testl    %esi, %esi
        movl    8(%ebp), %edx
        jne    LBB2_4
        jmp    LBB2_1
        .align    16, 0x90
    LBB2_8:
        incl    %eax
        incl    %edx
        movl    %edx, (%ecx)
    LBB2_4:
        testl    %edx, %edx
        jne    LBB2_5
        cmpb    $0, (%esi)
        jne    LBB2_8
        jmp    LBB2_6
        .align    16, 0x90
    LBB2_5:
        cmpl    %edx, %esi
        jne    LBB2_8
        jmp    LBB2_6
        .align    16, 0x90
    LBB2_3:
        leal    1(%edx,%eax), %esi
        incl    %eax
        movl    %esi, (%ecx)
    LBB2_1:
        movl    %edx, %esi
        addl    %eax, %esi
        je    LBB2_6
        cmpb    $0, (%esi)
        jne    LBB2_3
    LBB2_6:
        popl    %esi
        popl    %ebp
        ret
            
        pushl    %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %ecx
        xorl    %eax, %eax
        cmpb    $0, (%ecx)
        je    LBB1_4
        leal    8(%ebp), %edx
        .align    16, 0x90
    LBB1_2:
        cmpb    $0, 1(%ecx,%eax)
        leal    1(%eax), %eax
        jne    LBB1_2
        addl    %eax, %ecx
        movl    %ecx, (%edx)
    LBB1_4:
        popl    %ebp
        ret
            

    The code generated from the Iterable algorithm is far superior to that generated from the pair of iterators. In fact, if you check it against the assembly for the raw C-style iteration, you’ll find it’s almost identical.

    Iterators, Sentinels, and Equality

    But what does it mean to compare two objects of different types for equality? Or put in more formal terms, can the requirement that an Iterable’s iterator and sentinel satisfy the cross-type EqualityComparable concept be satisfied? I believe the answer is yes.

    Some background for the uninitiated: N3351 defines precisely when and how cross-type equality comparisons are meaningful. It’s not enough for the syntax “x==y” to be valid and yield a bool. If x and y have different types, the types of both x and y must themselves be EqualityComparable, and there must be a common type to which they can both be converted, and that type must also be EqualityComparable. Think of comparing a char with a short. It works because both char and short are EqualityComparable, and because they can both be converted to an int which is also EqualityComparable.

    Iterators are comparable, and sentinels are trivially comparable (they always compare equal). The tricky part is the common type requirement. Logically, every iterator and sentinel has a common type that can be constructed as follows: assume the existence of a new iterator type I that is a tagged union that contains either an iterator or a sentinel. When an iterator is compared to a sentinel, it behaves semantically as if both the iterator and the sentinel were first converted to two objects of type I — call them lhs and rhs — and then compared according to the following truth table:

    lhs is sentinel ? rhs is sentinel ? lhs == rhs ?
    true true true
    true false done(rhs.iter)
    false true done(lhs.iter)
    false false lhs.iter == rhs.iter

    If you’ve been following this series, the above truth table should ring a bell. It’s pretty much exactly the table we got when figuring out how c_string_range::iterator‘s equality operator should behave, and that’s no coincidence; that was a special case of this more general construction. This construction validates an intuition you might have after seeing the two classes I wrote, c_string_range and c_string_iterable. One is a pair of iterators, the other an iterator/sentinel pair, but they implement equivalent procedures for computing equality. We know they’re the same, and we feel in our guts we could build an equivalent Range out of every Iterable if we’re willing to sacrifice some performance. And now we know that’s true.

    Allowing direct comparison of iterators and sentinels lets us use the C++ type system to optimize a large category of iterations by eliminating branches from the equality comparison operator.

    Objections

    The idea of allowing begin and end iterators to have different types is not new, and it’s not mine. (In fact, many of you who have commented on the first two posts, either here or on reddit.com, have made precisely this suggestion.) I first heard about it from Dave Abrahams years ago. More recently, Dietmar Kuehl floated a similar idea on the Ranges mailing list. Sean Parent raised the following objection in a follow-up message:

    Again, I think this is putting too much on iterators. Algorithms that act with a sentinel termination or with a count are different beasts. See copy_n() and copy_sentinel()

    http://stlab.adobe.com/copy_8hpp.html

    For ranges – I certainly thing you should be able to construct a range with:

    1. a pair of iterators
    2. an iterator and a count
    3. an iterator and a sentinel value

    In which case, copy(r, out) can dispatch to the correct algorithm.

    If I’m understanding Sean correctly, he is arguing for 3 parallel range concept hierarchies: IteratorRange, CountedRange, and SentinelRange. These hierarchies would have no refinement relationships between them. The copy algorithm would have three underlying implementations, one for each concept hierarchy. There are 50 some odd algorithms that would need to be triplicated in this way. That’s a lot of code duplication.

    In fact, it’s worse than that because some algorithms are specialized to take advantage of more refined concepts. For instance, in libc++, the rotate algorithm dispatches to one of three implementations depending on whether you pass it forward, bidirectional, or random-access iterators. To accommodate Iterator, Counted, and SentinelRanges, we would need a grand total of 9 rotate algorithm implementations! I have nothing but respect for Sean Parent, but that’s madness. With the Iterable concept, Sean’s three separate hierarchies get unified under a single syntax that lets us write general algorithms while preserving performance characteristics. In other words, with Iterables, 3 implementations of rotate suffice.

    (Incidentally, the Iterable concept can neatly accommodate counted ranges. If you want to turn an iterator and a count into an Iterable, you can bundle the iterator and the count together into a new iterator type that decrements the count whenever the iterator is incremented. When comparing the iterator to the sentinel, it merely checks whether the count is zero.)

    Summary, For Now…

    At the beginning of this post I summarized some of the problems with pair-o’-iterator ranges. I showed how a new concept, Iterable, addresses the performance issues, and touched a bit on the issue of range implementation complexity. I haven’t yet covered how the Iterable concept helps with infinite ranges, or how to address the safety issue of passing an infinite range to an algorithm that can’t handle them. This post has run a bit long, so I’ll stop for now and address the other issues in the fourth and final installment. Hopefully, this has given you a few things to think about until then.

    If you want to download and play with the code, you can find it in the range-v3 repository on github. I’m happy to take suggestions and bug reports, but please don’t use this code for anything real. It’s untested and still evolving.

    Acknowledgements

    I’d like to thank Andrew Sutton for helping with the Concept Lite syntax and also for explaining the requirements of the cross-type EqualityComparable concept and generally improving and formalizing many of the ideas presented here. The article is immeasurably better for his many contributions.

    x
    x
  • Range Concepts, Part 2 of 4: Infinite Ranges

    In the last post, I tried to make delimited ranges fit into the STL and found the result unsatisfying. This time around I’ll be trying the same thing with infinite ranges and will sadly be reaching the same conclusion. But the exercise will point the way toward an uber-Range concept that will subsume delimited ranges, infinite ranges, and STL-ish pair-o’-iterator ranges.

    Infinite Ranges

    Building motivation for delimited ranges was fairly simple; we’re all familiar with the idea from null-terminated strings. The case for infinite ranges is bit harder to make. As C++ programmers, we don’t regularly bump into infinity. In other languages infinity is all in a day’s work. Haskell programmers can create an infinite list of integers as simply as typing [1..]. Does that break your brain? It shouldn’t. It’s a lazy list — the elements are generated on demand. All infinite ranges are necessarily lazy.

    What’s the use of that? Consider the take algorithm which constructs a new list from the first N elements of another list. It handles infinite lists with aplomb. Or consider what should happen when you zip an infinite list with a finite one. You end up with a finite list of element pairs. That’s a perfectly sensible thing to do.

    Supporting infinite ranges in a generic range library would be a boon, so it’s worth looking at what it does to the concepts.

    Infinite Ranges in the STL

    We might think of infinite ranges as a kind of degenerate delimited range where the delimiting predicate always returns false. When we’re trying to reach infinity, our work is never done. With that in mind, let’s implement an infinite range of integers starting at some value and ending never. It’s described below.

    struct iota_range
    {
    private:
        int i_;
    public:
        using const_iterator = struct iterator
          : boost::iterator_facade<
                iterator, int const,
                std::forward_iterator_tag
            >
        {
        private:
            bool sentinel_;
            int i_;
            friend class boost::iterator_core_access;
            friend struct iota_range;
            iterator(int i) : sentinel_(false), i_(i) {}
            bool equal(iterator that) const
            {
                return sentinel_ == that.sentinel_
                    && i_ == that.i_;
            }
            void increment() 
            {
                ++i_;
            }
            int const & dereference() const
            {
                return i_;
            }
        public:
            iterator() : sentinel_(true), i_(0) {}
        };
        constexpr explicit iota_range(int i = 0)
          : i_(i)
        {}
        iterator begin() const
        {
           return iterator{i_};
        }
        iterator end() const
        {
           return iterator{};
        }
        constexpr explicit operator bool() const
        {
           return true;
        }
    };
    

    With this range, we can do this:

    // Spew all the ints. WARNING: THIS NEVER ENDS!
    for( int i : iota_range() )
        std::cout << i << 'n';
    

    iota_range is a forward range; that is, its iterators model the ForwardIterator concept 1. They store both an integer and a Boolean signifying whether the iterator is a sentinel or not. The range’s begin iterator is not a sentinel, the end iterator is. Therefore, they will never compare equal, and we’ll count integers … forever!

    A Funny Thing Happened on the Way to Infinity

    What you’ll find when you use this range in your code is that some things will work as you expect and other things will spin off into hyperspace and never come back. Take a very simple example: std::distance. Presumably, you won’t be foolish enough to do this:

    iota_range iota;
    // Oops!
    auto dist = std::distance(iota.begin(), iota.end());
    

    What’s less clear is that you should never, ever, under any circumstance, pass this range directly or indirectly to any algorithm that does binary searching, including binary_search, lower_bound, upper_bound, and equal_range — despite the fact that iota_range is, in fact, a sorted forward range. Think about it: binary searching is a divide-and-conquer algorithm. Dividing an infinite range yields — surprise! — an infinite range. If you pass an iota_range to any of these algorithms, go get yourself a cup of coffee. You could be waiting a while.

    Performance Problems

    If you read the last blog post about delimited ranges, maybe you cringed a bit when you saw the implementation of iota_range::iterator::equal. It is our intention that an iota_range‘s iterator will never, ever finish iterating, so the termination condition should be a constant expression. Instead, we have this:

    bool equal(iterator that) const
    {
        return sentinel_ == that.sentinel_
            && i_ == that.i_;
    }
    

    That’s two runtime checks when it should be zero! As I showed last time, this can have a disastrous effect on the quality of the generated code.

    Possibly Infinite Ranges

    Infinite loops are one problem with infinite ranges, but there’s another more subtle problem, and unfortunately it already exists in the Standard Library. Take our old friend (and my favorite punching bag) std::istream_iterator. It is an input iterator, so it’s required to have an associated difference_type. In “Elements of Programming,” Alexander Stepanov (the father of the STL and of Generic Programming) says this about an Iterator’s difference type:

    DistanceType returns an integer type large enough to measure any sequence of applications of successor allowable for the type. 2

    For istream_iterator‘s, the difference_type is std::ptrdiff_t. Now, consider the following code:

    std::istream& sin = ...;
    std::istream_iterator<char> it{sin}, end;
    std::ptrdiff_t dis = std::distance(it, end);    
    

    This is perfectly reasonable and valid code. It pulls characters out of the istream, counts them, and discards them. Now, imaging sin is pulling characters from the network, and that this code runs for days, pulling billions and billions of characters off the net. What happens when a ptrdiff_t isn’t big enough to hold the result? Answer: undefined behavior. In practice, you’ll get garbage, but in principle, anything could happen.

    To me, that’s a little disconcerting. An iterator’s difference_type should be big enough to hold the distance between any two iterators. Since input streams are unbounded in principle, there is no scalar signed integer type that’s big enough. Huh. We’re forced to conclude that the validity of istream_iterator‘s increment operation is limited by the size of its difference_type, or that istream_iterator‘s difference_type is wrong. Again: Huh.

    Summary, For Now…

    Infinite ranges are useful, but they have real problems given the current definition of the STL. You might think that disallowing infinite ranges avoids the problem, but it’s more fundamental than that. In fact, some problems exist today. It’s hard to fix the difference_type overflow issue in the STL today (apart from telling people to be careful), but it’s worth considering whether a new range-based interface can help. (So as not to raise expectations, I’ll say now that this is a vexing problem that I don’t yet have a great solution to.)

    Summing up, here are the issues I’ve identified so far with STL-ish pair-o’-iterators-style ranges:

    • Delimited and infinite ranges generate poor code
    • They are forced to model weaker concepts than they might otherwise
    • Also, they’re awkward to implement
    • It’s too easy to pass an infinite range to an algorithm that can’t handle it
    • Possibly-infinite ranges can overflow their difference_type

    In the next installment, I’ll describe the conceptual foundations of my new range library that strikes at the root of these problems. Stay tuned.


    1. Actually, this is a bit of a lie. Forward iterators aren’t supposed to return references to objects inside them. Please ignore this for the sake of discussion.↩

    2. Stepanov, A; McJones, P. Elements of Programming. Addison-Wesley. 2009.↩

    x
    x
  • Range Concepts, Part 1 of 4: Delimited Ranges

    I’ve been digging into ranges recently, and I’m finding them to be more than just a pair of iterators. In a series of posts, I’ll be expanding the notion of what a range is to cover some kinds of ranges not easily or efficiently expressible within the STL today: delimited ranges and infinite ranges. This post deals with the problems of representing delimited ranges with STL iterators.

    Delimited Ranges

    When groping about for concepts, it’s essential to have some concrete examples in mind. So when I say “delimited range,” think: null-terminated C-style string. The end of the sequence is not some known position; rather, it’s an unknown position at which we expect to find some delimiter, or more generally, at which some predicate becomes true. Another example, interestingly, is an istream range. The delimiter in that case is when the istream extractor fails. And yet, the standard has std::istream_iterator, so clearly it’s not impossible to shoehorn delimited ranges into the STL. I’ll show how, and explain why I use the term “shoehorn.”

    Delimited Ranges in the STL

    To prove my “shoehorn” allegation, here is a delimited range over a C-style string with fully STL-compliant iterators:

    #include <cassert>
    #include <iostream>
    #include <boost/iterator/iterator_facade.hpp>
    
    struct c_string_range
    {
    private:
        char const *str_;
    public:
        using const_iterator = struct iterator
          : boost::iterator_facade<
                iterator
              , char const
              , std::forward_iterator_tag
            >
        {
        private:
            friend class boost::iterator_core_access;
            friend struct c_string_range;
            char const * str_;
            iterator(char const * str)
              : str_(str)
            {}
            bool equal(iterator that) const
            {
                return str_
                    ? (that.str_ == str_ ||
                         (!that.str_ && !*str_))
                    : (!that.str_ || !*that.str_);
            }
            void increment()
            {
                assert(str_ && *str_);
                ++str_;
            }
            char const& dereference() const
            {
                assert(str_ && *str_);
                return *str_;
            }
        public:
            iterator()
              : str_(nullptr)
            {}
        };
        c_string_range(char const * str)
          : str_(str)
        {
            assert(str_);
        }
        iterator begin() const
        {
            return iterator{str_};
        }
        iterator end() const
        {
            return iterator{};
        }
        explicit operator bool() const
        {
            return !!*str_;
        }
    };
    
    int main()
    {
        for(char c : c_string_range("hello world!"))
            std::cout << c;
        std::cout << 'n';
    }
    

    The code traverses the sequence of characters without first computing its end. It does it by creating a dummy end iterator — a sentinel — such that any time a real iterator is compared to it, it checks to see if the real iterator points to the null terminator. All the gross logic is there in the c_string_range::iterator::equal member function. Nobody would call this code beautiful or elegant.

    In the STL today, ranges are specified with two iterators: the begin and the end. For iterators like std::istream_iterator or c_string_range::iterator where an iterator can be a sentinel, it adds branches to the iterator equality test since you first have to determine if one or both of the iterators are sentinels. The expression a == b is evaluated according to the following truth table:

    a == end ? b == end ? a == b ?
    true true true
    true false *b == 0
    false true *a == 0
    false false &*a == &*b

    The above tests must be evaluated at runtime! There’s no way to know a priori whether an iterator is a real iterator or a dummy one. And all that checking is expensive. That’s what I mean when I say that delimited ranges can be “shoehorned” into the STL. It’s not a comfortable fit.

    The Compiler Agrees

    And when I say it’s an uncomfortable fit, that’s not just my opinion. I generated code for the following two functions:

    int c_strlen(char const *sz)
    {
        int i = 0;
        for(; *sz; ++sz)
            ++i;
        return i;
    }
    
    int range_strlen(
        c_string_range::iterator begin,
        c_string_range::iterator end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    

    The two functions do exactly the same thing, so in theory they should generate the same code. Our Spidey-sense should be tingling though after seeing the complicated conditional logic in c_string_range::iterator::equal. Indeed, the code they generate is far from comparable:

    c_strlen range_strlen
        pushl   %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %ecx
        xorl    %eax, %eax
        cmpb    $0, (%ecx)
        je  LBB1_3
        xorl    %eax, %eax
        .align  16, 0x90
    LBB1_2:
        cmpb    $0, 1(%ecx,%eax)
        leal    1(%eax), %eax
        jne LBB1_2
    LBB1_3:
        popl    %ebp
        ret
            
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %esi
        leal    8(%ebp), %ecx
        movl    12(%ebp), %esi
        xorl    %eax, %eax
        testl   %esi, %esi
        movl    8(%ebp), %edx
        jne LBB2_4
        jmp LBB2_1
        .align  16, 0x90
    LBB2_8:
        incl    %eax
        incl    %edx
        movl    %edx, (%ecx)
    LBB2_4:
        testl   %edx, %edx
        jne LBB2_5
        cmpb    $0, (%esi)
        jne LBB2_8
        jmp LBB2_6
        .align  16, 0x90
    LBB2_5:
        cmpl    %edx, %esi
        jne LBB2_8
        jmp LBB2_6
        .align  16, 0x90
    LBB2_3:
        leal    1(%edx,%eax), %esi
        incl    %eax
        movl    %esi, (%ecx)
    LBB2_1:
        movl    %edx, %esi
        addl    %eax, %esi
        je  LBB2_6
        cmpb    $0, (%esi)
        jne LBB2_3
    LBB2_6:
        popl    %esi
        popl    %ebp
        ret
            

    Oh my! Look at all those tests and branches! The above code was generated with clang 3.4 with -O3 -DNDEBUG. I should add that in practice, the compiler can often generate better code for range_strlen. If the compiler can infer statically that end is in fact a sentinel, and if the definition of range_strlen is available for inlining, then the compiler will generate better code. Near-optimal, in fact. But those are some big “If”s.

    Besides, people generally don’t contort themselves by writing the c_string_range class when dealing with delimited strings. They call strlen and then some algorithm, traversing the range twice instead of once. But consider the case of the istream range. You can’t do the same trick with an input range because merely finding the end iterator consumes the range! Now we see why std::istream_iterator has a dummy sentinel. There’s simply no other way.

    And as a final note, observe that c_string_range::iterator is a forward iterator, despite the fact that the raw char const* it wraps is random-access. That’s because the sentinel cannot be decremented. The range’s iterator can only be as powerful as its sentinel, which is pretty darn weak.

    So What?

    So we can’t efficiently use STL algorithms on C-style strings. Big deal, right? Actually, it is. It means that pretty much all generic string algorithms cannot be used on C-style strings. Look at all the juicy string algorithms in Boost.String_algo. The docs say this about the string types it supports:

    “Definition: A string is a range of characters accessible in sequential ordered fashion. […] First requirement of string-type is that it must accessible using Boost.Range. This facility allows to access the elements inside the string in a uniform iterator-based fashion.”

    No love for C-style strings from Boost.String_algo. And by the way, what do you think happens when you call std::regex_search with a C-style string? It first calls strlen! So even if your string is megabytes long and the match is at the very front, you first have to traverse the entire string just so that you know where the end is. Which is all totally pointless.

    “You shouldn’t be using C-style strings anyway,” you say. But the problem is bigger than C-style string. All delimited ranges have this problem. Just within the standard library, there are istream_iterator, istreambuf_iterator, regex_iterator, and regex_token_iterator, all of which have dummy sentinels, all of which have been shoehorned in like I’ve shown above. I’m sure you can think of others.

    Dietmar Kuehl alerted me to another interesting case. Have you ever wanted to call a generic algorithm but couldn’t because you wanted to break out of the loop early under some condition? Imagine that you could build a delimited range with that predicate and the end iterator. Now you can pass that range to an algorithm and it would stop either when the predicate becomes true or when you reach the end of the sequence. Voila! Standard algorithms just got a lot more useful. But this iterator type would have to be shoehorned in like the others, and you wouldn’t be able to call any algorithm that required more than forward iterators since you can’t decrement the sentinel.

    Conclusion, For Now…

    What’s my point? My point is this: the pair-of-iterators range abstraction that we are familiar with and that was designed to have low abstraction cost has real abstraction cost that cannot be avoided for delimited ranges. It also forces delimited ranges to model weaker concepts than they might otherwise, and makes their implementation awkward. What’s the solution? I do have a concrete suggestion, but we’re not there yet. First I want to talk about infinite ranges, and then we’ll see how delimited, infinite and pair-o’-iterators ranges can all be subsumed into a larger Range concept. Tune in next time…

    Acknowledgements

    I’d like to Dietmar Kuehl and Andrew Sutton for helping me formulate my range ideas and for reviewing this article.

    x
    x
  • Concept Checking in C++11

    This post describes some utilities I’ve recently developed for doing concept checking in C++11. These utilities are part of an ongoing project to reimplement ranges, also for C++11, but I think the concept checking utilities are useful and interesting in their own right.

    Concepts, the Saga So Far

    (Feel free to skip this section if you already know what concepts are.)

    The story of concept checking in C++ is long and quite dramatic. They were added to C++0x, they were hotly debated, they were ripped out (along with lots of greying hair), hands were wrung, chests beaten, sackcloth rent … Biblical stuff, truly. OK, maybe not, but it was dramatic. Anyway, there’s a new proposal to add them back, so it’s clear lots of people want concepts bad.

    But let’s back up. What are concepts? In a sense, programmers have been using concepts since 1998 or even earlier, when the Standard Template Library first became a thing. You probably know what an iterator is, and you know there’s a difference between a random-access iterator, like std::vector‘s iterators, and bidirectional iterators, like std::list‘s. Things like “random-access iterator” and “bidirectional iterator” are concepts. Types don’t have to inherit from any special base class to be a random-access iterator. They just have to support a certain syntax and semantics. And the random-access iterator concept is a refinement of bidirectional iterator; the former supports all the syntax and semantics of the latter (e.g., increment and decrement), plus some additional stuff (e.g., being able to advance an iterator by n positions in O(1) time).

    Concepts make it possible to define polymorphic algorithms: algorithms that work with objects of many different types. And they do it with very loose coupling and high performance. If your algorithm only relies on the syntax and semantics promised by the concept, then it should Just Work. And there’s the rub. Today, there’s no way to say in code that a certain algorithm requires random-access iterators, and if you pass it a bidirectional iterator, you’re sure to find out in the most unpleasant way. Hence the desire to add concept checking to the language proper.

    Concepts, A New Hope?

    Enough back-story. Show me the code, right? Here’s the full refinement hierarchy for the iterator concepts as defined with my utility.

    struct Iterator
      : refines<CopyConstructible, CopyAssignable,
                Destructible>
    {
        // Valid expressions
        template<typename T>
        auto requires(T && t) -> decltype(
            concepts::valid_expr(
                *t,
                concepts::has_type<T &>(++t)
            ));
    };
    
    struct OutputIterator
      : refines<Iterator(_1)> // OutputIterator<T,U> refines
    {                         // Iterator<T>
        template<typename T, typename O>
        auto requires(T && t, O && o) -> decltype(
            concepts::valid_expr(
                t++,
                *t = o,
                *t++ = o
            ));
    };
    
    struct InputIterator
      : refines<Iterator, Comparable>
    {
        template<typename T>
        auto requires(T && t) -> decltype(
            concepts::valid_expr(
                t++,
                concepts::convertible(*t, *t++)
            ));
    };
    
    struct ForwardIterator
      : refines<InputIterator>
    {
        template<typename T>
        auto requires(T && t) -> decltype(
            concepts::valid_expr(
                concepts::same_type(*t, *t++)
            ));
    };
    
    struct BidirectionalIterator
      : refines<ForwardIterator>
    {
        template<typename T>
        auto requires(T && t) -> decltype(
            concepts::valid_expr(
                concepts::has_type<T &>( --t ),
                concepts::same_type(*t, *t--)
            ));
    };
    
    struct RandomAccessIterator
      : refines<BidirectionalIterator>
    {
        template<typename T>
        auto requires(T && t) -> decltype(
            concepts::valid_expr(
                concepts::model_of<SignedIntegral>(t-t),
                t = t + (t-t),
                t = (t-t) + t,
                t = t - (t-t),
                t += (t-t),
                t -= (t-t),
                concepts::same_type(*t, t[t-t]),
                concepts::model_of<Orderable>(t)
            ));
    };
    

    This might look a little strange at first glance, so let me step you through it. The first two lines…

    struct Iterator
      : refines<CopyConstructible, CopyAssignable,
                Destructible>
    

    … says that there is a concept called Iterator that refines the concepts CopyConstructible, CopyAssignable, and Destructible. Surely all iterators must support those basic operations. If the concept you want to define doesn’t refine any other concepts, you can leave that part off.

    The next few lines describes the so-called valid expressions: valid syntax that all iterators must support:

    template<typename T>
    auto requires(T && t) -> decltype(
        concepts::valid_expr(
            *t,
            concepts::has_type<T &>(++t)
        ));
    

    You must be able to dereference an iterator and increment it, and the result of the increment operation must have type T &. This is true of all iterators. When you’re defining your concept’s valid expressions, you do so by following the above pattern: a requires member function that takes one or more objects by rvalue ref, and a trailing return type with decltype(concepts::valid_expr(/*...*/)) with your valid expressions. And that’s pretty much it for the concept definitions. There’s some utilities like has_type, same_type, and model_of for concept check-y sorts of things, but those are all details.

    Concept Checking

    We’ve seen what concept definitions look like, now let’s see how to use them. Imagine all the above definitions are in a concepts namespace. Let’s define some helpers for testing certain types against the concept definitions. They look like this:

    template<typename T>
    constexpr bool Iterator()
    {
        return concepts::models<concepts::Iterator, T>();
    }
    
    template<typename T, typename O>
    constexpr bool OutputIterator()
    {
        return concepts::models<concepts::OutputIterator, T, O>();
    }
    
    template<typename T>
    constexpr bool InputIterator()
    {
        return concepts::models<concepts::InputIterator, T>();
    }
    
    template<typename T>
    constexpr bool ForwardIterator()
    {
        return concepts::models<concepts::ForwardIterator, T>();
    }
    
    template<typename T>
    constexpr bool BidirectionalIterator()
    {
        return concepts::models<concepts::BidirectionalIterator, T>();
    }
    
    template<typename T>
    constexpr bool RandomAccessIterator()
    {
        return concepts::models<concepts::RandomAccessIterator, T>();
    }
    

    Notice how these concept checkers are constexpr Boolean functions. The concepts::models function will return true if the given type(s) model the concept, and false otherwise. Easy. And note that so far, we haven’t used a single macro because I hate macros.

    Now when you are wondering whether a certain type models a concept, you can get the answer as a compile-time Boolean. Say, for instance, that you are writing something like the std::advance algorithm. You want to make sure that the two arguments are an input iterator and a integral type, respectively:

    template<typename InIt, typename Diff>
    void advance(InIt & it, Diff d)
    {
        static_assert(ranges::Integral<Diff>(),
                      "Diff isn't integral");
        static_assert(ranges::InputIterator<InIt>(),
                      "InIt isn't an input iterator");
        // ...
    }
    

    If you’re not allergic to macros, you can also do this:

    template<typename InIt, typename Diff>
    void advance(InIt & it, Diff d)
    {
        CONCEPT_ASSERT(ranges::Integral<Diff>());
        CONCEPT_ASSERT(ranges::InputIterator<InIt>());
        // ...
    }
    

    (As you can see, in my code all the concept checking function are in the ranges namespace.) This is pretty nice. If someone calls advance with the wrong types, they’ll get a sensible error message. But maybe you want something else. Maybe there are lots of advance functions, and you want this overload to silently go away if the types don’t model the concepts. Then you can do this:

    template<typename InIt, typename Diff,
             typename = concepts::requires_t<
                            ranges::Integral<Diff>() &&
                            ranges::InputIterator<InIt>()>>
    void advance(InIt & it, Diff d)
    {
        // ...
    }
    

    This uses SFINAE to make the advance function disappear when the concept requirements are not satisfied. That works, but it’s getting a bit ugly. Maybe it’s better to hold our noses and use a macro:

    template<typename InIt, typename Diff,
             CONCEPT_REQUIRES(ranges::Integral<Diff>() &&
                              ranges::InputIterator<InIt>())>
    void advance(InIt & it, Diff d)
    {
        // ...
    }
    

    I hate macros, but I can live with that.

    Concept-Based Overloading

    If you know anything about std::advance, you might know why I picked it as an example. advance advances an iterator by a certain number of positions. Most iterators must be bumped forward n times, which is slow. But if an iterator is random-access, you can just add n to it and be done. How would you achieve that with my new concept-checking utilities?

    In C++98, this is accomplished with iterator tag types and tag dispatching. Unfortunately, tag dispatching is still the best we can do in C++11, which is why we really need a language feature. But with my code, becomes quite a bit easier. The concept definitions can themselves be used as tags. Let’s see how.

    The first question to answer is, given an iterator type, what is the most refined iterator concept that it models? For a type like int* it should be RandomAccessIterator, but for std::list::iterator it should be BidirectionalIterator. You can get that information with the help of a utility called most_refined_t. Here we use most_refined_t to implement an iterator_concept_t alias that tells you what concept an iterator type models:

    template<typename T>
    using iterator_concept_t =
        concepts::most_refined_t<
            concepts::RandomAccessIterator, T>;
    

    most_refined_t does a breadth-first search of the refinement hierarchy rooted at concepts::RandomAccessIterator, looking for the most refined concept modeled by type T. Here’s how we can use it to optimally implement advance:

    // Random-access iterators go here
    template<typename RndIt, typename Diff>
    void advance_impl(RndIt & it, Diff d,
                      ranges::concepts::RandomAccessIterator)
    {
        it += d;
    }
    
    // All other iterator types go here
    template<typename InIt, typename Diff>
    void advance_impl(InIt & it, Diff d,
                      ranges::concepts::InputIterator)
    {
        for(; d != 0; --d)
            ++it;
    }
    
    template<typename InIt, typename Diff,
             CONCEPT_REQUIRES(ranges::InputIterator<InIt>() &&
                              ranges::Integral<Diff>())>
    void advance(InIt it, Diff d)
    {
        advance_impl(it, d, ranges::iterator_concept_t<InIt>{});
    }
    

    As you can see, concept-based overloading is accomplished by dispatching to the proper implementation based on the concept that a particular type models. This all works just based on the concept definitions which, if you recall, only required you to specify the refinements and the valid expressions declaratively. You didn’t have to define any separate tags or any traits or metafunctions. Not shabby.

    What’s Missing?

    The big missing piece of this puzzle is the ability to automatically check an algorithm against the requires clauses. It’s all well and good that the advance algorithm says it needs only input iterators. But what if its implementation actually makes some other assumption? You wouldn’t know until you tried to call the algorithm with a type that doesn’t satisfy the assumption. That’s the state of the art, I’m afraid, and there’s nothing I can do about it. Sorry.

    Making the Abstract Concrete

    My concept-checking library isn’t perfect. It’s really a pale approximation of what true language support would be like. Heck, it isn’t even a library yet. But in my limited experience using this utility in my range code so far, it has real benefits. I can create rich overload sets and tune which overload gets selected by simply declaring what concepts the types must model. And defining the concepts is easy. Fun, even. It gives me more confidence when writing generic code that I’m actually going to get the behavior I expect.

    So, if you like, leave me a comment with your thoughts. Would you find this useful? Is there a direction you’d like to see this go? Should I try (in my ample free time ) to turn this into a proper library, possibly as a modern replacement for Boost.Concept_check? Give me your thoughts.

    For reference, you can find the (woefully under-commented and undocumented) code here.

    x
  • Input Iterators vs Input Ranges

    This post was inspired by some shortcomings of the std::getline solution I described in my previous post, which just goes to show that there is no interface so simple that it can’t be done wrong. Or at least sub-optimally.

    Input Iterators and Lazy Ranges

    In the previous article, I analyzed the interface of std::getline and proposed a range-based solution as a better alternative. Users of the new range-based getlines API would read lines from a stream like this:

    for(std::string const & line : getlines(std::cin))
    {
        use_line(line);
    }
    

    The range object returned from getlines is lazy; that is, it fetches lines on demand. It’s a good design, and I’m still happy with it. The implementation leaves much to be desired though. Both the range object itself, as well as the iterators it yields, are fatter than they need to be. That got me thinking about std::istream_iterator, and input iterators and ranges in general. My conclusion: Naked input iterators like std::istream_iterator that don’t “belong” to a range have serious problems.

    Fat Input Iterators

    If you’re not already familiar with std::istream_iterator, take a minute to look it up in your favorite C++ reference. It is parametrized on the type of thing you want to extract from a stream. An istream_iterator<int> reads ints, an istream_iterator<string> reads strings, etc. Although the implementation is unspecified, reading an element would typically happen first when the iterator is constructed, and then each time the iterator is incremented. The element is stored in a data member so that it can be returned when you dereference the iterator. OK so far?

    The implication for istream_iterator<string> is that it is a hulking behemoth of an iterator. Not only is it fat because it holds a string, but copying one means copying a string, too. That’s potentially a dynamic allocation, just from copying an iterator! STL algorithms generally assume iterators are cheap to copy and take them by value nonchalantly. What’s more, a default-constructed istream_iterator<string> is used as a dummy end-of-sequence iterator. Naturally, it contains a string too, but it never uses it! istream_iterator definitely needs to go on a diet. We’ll fix that, but we’re not done describing the problems yet. Read on.

    Surprising Side-Effects

    Say we wanted to return a range of istream_iterator<string>s. We could return a std::pair of them, and that would work, sort of. Better, we could return a boost::iterator_range (which is basically a std::pair of iterators with begin and end member functions) to get something that users could iterate over with a range-based for loop:

    // Return a lazy range of strings
    boost::iterator_range<std::istream_iterator<std::string>>
    get_strings( std::istream & sin )
    {
        return boost::make_iterator_range(
            std::istream_iterator<std::string>{sin},
            std::istream_iterator<std::string>{}
        );
    }
    
    //...
    
    for(std::string const & str : get_strings( std::cin ))
    {
        use_string(str);
    }
    

    But think of the waste: the range holds two iterators, each of which holds a string and a reference to the stream. Wouldn’t it be smarter if the returned range just held a reference to the stream, and constructed the iterators on-demand in its begin and end member functions, like this:

    template< class T >
    class istream_range
    {
        std::istream & sin_;
    public:
        using iterator = std::istream_iterator<T>;
        using const_iterator = iterator;
    
        explicit istream_range( std::istream & sin )
          : sin_(sin)
        {}
        iterator begin() const
        {
            return std::istream_iterator<T>{sin_};
        }
        iterator end() const
        {
            return std::istream_iterator<T>{};
        }
    };
    

    OMG, isn’t this soooo clever? The range object went from about 24 bytes (with libstdc++ 4.7), to 4 bytes — the size of just one pointer! And if you play around with istream_range, it will seem to work. Check it out:

    // Read a bunch of strings from a stream
    std::istringstream sin{"This is his face"};
    
    for(auto const & str : istream_range<std::string>{sin})
    {
        std::cout << str << std::endl;
    }
    

    As we might expect, the above prints:

    This
    is
    his
    face
    

    But all is not roses. Take a look at this:

    std::istringstream sin{"This is his face"};
    istream_range<std::string> strings{sin};
    
    if(strings.begin() != strings.end())
        std::cout << *strings.begin() << std::endl;
    

    This code checks to see if the range is non-empty, and if so it prints the first element of the range. What would you expect this to print? This, right? After all, that’s the first string in the stream. If you try it, this is what you’ll get:

    is
    

    Huh? That’s hardly what any reasonable person would expect. Chalk this gotcha up to a quirk of the implementation of istream_iterator. As mentioned above, when you construct one from a stream, it eagerly fetches a value out of the stream and saves it (or, most implementations do). That’s fine, unless you happen to throw that iterator away and construct a new one, which fetches a second value from the stream. That, sadly, is what the above code is doing, but it’s not obvious.

    If the fatness was the first problem with std::istream_iterator, the second is that its constructor has surprising side-effects.

    Lone Range-er to the Rescue!

    The solution to istream_iterator‘s woes will be to replace it with istream_range. Put simply, if we’re reading strings from a stream, the string needs to live somewhere. The iterator seemed like the logical place when we were all thinking strictly in terms of iterators. But with ranges, we now have a much better place to put it: in the range object.

    With the string safely tucked away in the range object, we neatly side-step the issue of fat istream iterators. The iterator only needs to hold a pointer to the range. It goes without saying that the iterator cannot outlive the range that produced it, but that’s true of all the standard containers and their iterators.

    The range object also gives us a better place to put the surprising side-effect: in the range object’s constructor. By moving the side-effect out of the iterator’s constructor, it is now perfectly acceptable to construct the iterators on-demand in the begin and end member functions. We’re left with an optimally small range — it holds only a string and an istream & — and an optimally small and efficient iterator — it holds only a pointer.

    Without further ado, here is the complete solution:

    template< class T >
    class istream_range
    {
        std::istream & sin_;
        mutable T obj_;
    
        bool next() const
        {
            return sin_ >> obj_;
        }
    public:
        // Define const_iterator and iterator together:
        using const_iterator = struct iterator
          : boost::iterator_facade<
                iterator,
                T const,
                std::input_iterator_tag
            >
        {
            iterator() : rng_{} {}
        private:
            friend class istream_range;
            friend class boost::iterator_core_access;
    
            explicit iterator(istream_range const & rng)
              : rng_(rng ? &rng : nullptr)
            {}
    
            void increment()
            {
                // Don't advance a singular iterator
                BOOST_ASSERT(rng_);
                // Fetch the next element, null out the
                // iterator if it fails
                if(!rng_->next())
                    rng_ = nullptr;
            }
    
            bool equal(iterator that) const
            {
                return rng_ == that.rng_;
            }
    
            T const & dereference() const
            {
                // Don't deref a singular iterator
                BOOST_ASSERT(rng_);
                return rng_->obj_;
            }
    
            istream_range const *rng_;
        };
    
        explicit istream_range(std::istream & sin)
          : sin_(sin), obj_{}
        {
            next(); // prime the pump
        }
    
        iterator begin() const { return iterator{*this}; }
        iterator end() const   { return iterator{};     }
    
        explicit operator bool() const // any objects left?
        {
            return sin_;
        }
    
        bool operator!() const { return !sin_; }
    };
    

    This solution has a major advantage over std::istream_iterator even in the pre-ranges world of C++98: the iterators are as svelte and cheap to copy as a single pointer. One might go so far as to wonder how a potentially inefficient and error-prone component as istream_iterator ever made it into the standard in the first place. (But, I just mentioned “efficient” and “iostreams” in the same sentence, so how smart am I, right Andrei?)

    As an added bonus, I added a cute contextual conversion to bool for testing whether the range is empty or not. That lets you write code like this:

    if( auto strs = istream_range<std::string>{std::cin} )
        std::cout << *strs.begin() << std::endl;
    

    If you don’t like the Boolean conversion trick, you can do it the old, boring way too:

    istream_range<std::string> strs{std::cin};
    if( strs.begin() != strs.end() )
        std::cout << *strs.begin() << std::endl;
    

    You can call strs.begin() as many times as you like, and it has no untoward side-effects. Adapting this code to improve my getlines implementation from the previous post is a trivial exercise.

    Home on the Range

    In the post-ranges world, the advantages of istream_range over istream_iterator are even clearer. As I mentioned in my previous post ranges are awesome because they compose. With filters and transformers and zippers and the whole zoo of range adapters, you can do things with ranges and range algorithms that you wouldn’t dream of doing with raw iterators before.

    Conclusion

    So far, the ranges discussion as I’ve heard it has been framed mostly in terms of ranges’ added convenience and power. To this impressive list of advantages, we can now add efficiency. Win, win, win.

    Caveat to the Boost.Range Users

    Please read this if you are an avid user of Boost’s range adapters. As they are currently written, they interact poorly with the istream_range I’ve presented here. Some things will work, like this:

    // read in ints, echo back the evens
    auto is_even = [](int i) {return 0==i%2;};
    boost::copy( istream_range<int>{std::cin}
                   | boost::adaptors::filtered(is_even),
                 std::ostream_iterator<int>(std::cout) );
    

    And some things will fail, like this:

    // read in ints, echo back the evens
    auto is_even = [](int i) {return 0==i%2;};
    auto evens = istream_range<int>{std::cin}
                   | boost::adaptors::filtered(is_even);
    boost::copy( evens, std::ostream_iterator<int>(std::cout) );
    

    The problem is that the temporary istream_range<int> goes out of scope before we have a chance to iterate over it. Had we gone with an iterator_range< std::istream_iterator<int> >, it would have actually worked, but only because of a quirk of the current Boost.Range implementation. The Boost.Range adapters only work when either (A) the adapted range happens to be an lvalue, or (B) the range’s iterators can outlive their range. These less-than-ideal assumptions made sense in C++98, but not in C++11. On modern compilers, Boost.Range can and should store a copy of any adapted rvalue ranges. In my opinion, it’s time for a range library for the modern world.

    x
  • Out Parameters, Move Semantics, and Stateful Algorithms

    At GoingNative back in September, Andrei Alexandrescu posed an interesting question about API design and C++11 that has had me scratching my head for a month. It was about the design of std::getline:

    // Read a line from sin and fill in buf. Return sin.
    std::istream& getline(std::istream& sin, std::string& buf)
    {
        buf.clear();
        // ... fill in buf
        return sin;
    }
    

    Seasoned programmers recognize this pattern: The function takes the buffer by non-const reference and fills it in. They also know why the interface is designed this way: Because containers like std::string are too expensive to copy to consider returning one by value. APIs designed like this have traditionally had the benefit of being efficient, at the expense of some awkwardness at the call site:

    std::string buf;
    std::getline(std::cin, buf);
    use_line(buf);
    

    In C++11, standard containers like std::string are moveable, so returning one by value is darn near free. So, perhaps a better API design would look like this:

    // Should getline look like this instead?
    std::string getline(std::istream& sin)
    {
        std::string buf;
        // ... fill in buf
        return buf; // This gets moved out efficiently
    }
    

    That allows a more concise, natural usage, and doesn’t force the user to create a named variable:

    use_line(getline(std::cin));
    

    That’s nice, right? I mean, aside from the obvious shortcoming that now you can’t tell whether getline succeeded or not. Oops. But even overlooking that, there’s an issue here.

    Performance, Performance, Performance

    You might think that because of move semantics, we don’t have to worry about the lousy performance of returning expensive collections by value, and you’d be right. Sort of. But consider this use of getline:

    std::string buf;
    while(std::getline(std::cin, buf))
        use_line(buf); 
    

    Now consider what this code would be doing if, instead of taking buf as an out parameter, getline created a new string each time and returned it by value. Well, it’s creating a new string each time, duh. But the code above doesn’t do that. After a few times through the loop, buf will probably be big enough to hold whatever lines will be read next, and that space can be reused with no further allocations. Much, much faster.

    Back To The Drawing Board

    During GoingNative, Andrei left getline there. (It turns out he prefers a different design, and we’ll be arriving at a similar conclusion.) I wanted to continue the discussion. Out parameters are ugly and awkward to use, they hurt API composability, they force you to declare objects and initialize them in separate steps, they cause acne, etc. Surely something could be done!

    I studied the problematic code some more:

    std::string buf;
    while(std::getline(std::cin, buf))
        use_line(buf); 
    

    What is this code doing? It’s reading a bunch of lines and processing them one at a time, right? You might even say, it’s returning a range of lines. Then it hit me: std::getline is the wrong API! It should be called getlines (plural), and it should return a range of strings. Take a look:

    for(std::string& buf : getlines(std::cin))
        use_line(buf);
    

    This API feels right-er to me. Not only is it easier to use (look ma! one fewer line!), it doesn’t force a two-step initialization of any objects, and ranges and range operations compose. (More on that later.) It also doesn’t suffer from the performance problems of my first attempt, although it takes some work to see why.

    Lazy Ranges

    What does my getlines function return? Surely it doesn’t fill in a std::vector of string‘s and return that. That would be (a) dumb, (b) expensive, and (c) impossible in practice since a potentially infinite number of lines could be read from an istream. Instead, getlines does something smarter: it returns a lazy range.

    A lazy range is something that generates elements on demand. The STL already has such a thing: std::istream_iterator. You can create a range out of istream_iterators that pulls characters — or ints or whatever — from an istream on demand. We need something like that, but for lines.

    Unfortunately, we can’t press istream_interator into service for us. Instead, we need to write our own iterator type, and build a valid range out of that. This is a painful and verbose programming exercise, but Boost.Iterator can help. It has some helpers that let you build iterators from a fairly minimal interface. Without further ado, here is the lines_iterator:

    struct lines_iterator
      : boost::iterator_facade<
            lines_iterator,
            std::string,            // value type
            std::input_iterator_tag // category
        >
    {
        lines_iterator() : psin_{}, pstr_{}, delim_{} {}
        lines_iterator(std::istream *psin,
                       std::string *pstr,
                       char delim)
            : psin_(psin), pstr_(pstr), delim_(delim)
        {
            increment();
        }
    private:
        friend class boost::iterator_core_access;
    
        void increment()
        {
            if(!std::getline(*psin_, *pstr_, delim_))
                *this = lines_iterator{};
        }
    
        bool equal(lines_iterator const & that) const
        {
            return pstr_ == that.pstr_;
        }
    
        std::string & dereference() const
        {
            return *pstr_;
        }
    
        std::istream *psin_;
        std::string *pstr_;
        char delim_;
    };
    

    The magic happens when you increment a lines_iterator, which happens in lines_iterator::increment. std::getline is called, and it fills in a buffer referred to by pstr_. Note that it uses the same buffer every time. And when you dereference a lines_iterator, it returns a reference to that buffer. No copying, no unnecessary allocation.

    Where does the buffer referred to by pstr_ live? In the lines_range object, which is returned by getlines.

    using lines_range_base =
        boost::iterator_range<lines_iterator>;
    
    struct lines_range_data {std::string str_;};
    
    struct lines_range
        : private lines_range_data, lines_range_base
    {
        explicit lines_range(std::istream & sin,
                             char delim = 'n')
            : lines_range_base{
                  lines_iterator{&sin, &str_, delim},
                  lines_iterator{}}
        {}
    };
    
    inline
    lines_range getlines(std::istream& sin, char delim = 'n')
    {
        return lines_range{sin, delim};
    }
    

    lines_range is really just a boost::iterator_range of lines_iterators. Some contortion was needed to initialize the str_ member before the iterator_range constructor was called (hence the need for lines_range_data), but that’s just an implementation artifact.

    The long and short of it is this: when you call getlines, you get back a lines_range object, which is basically a free operation. Now you can call .begin() and .end() on it, or directly iterate over it using a range-based for loop, like I showed. No more memory allocations are done using this interface than with the original std::getline API. Nice, eh?

    Composability of Ranges and Range Algorithms

    There’s lots of reasons to prefer the range-based getlines API — and range-based interfaces in general. The most immediate benefit is that people can use range-based for loops, as I showed above. But the real power comes once you start using range algorithms and range adaptors. Both Boost and Adobe’s ASL provide powerful utilities for working with ranges, and the C++ Standardization Committee has a working group dedicated to ranges for some future version of the standard. And for good reason! Range operations compose, so for instance you could do something like this:

    // Read some lines, select the ones that satisfy
    // some predicate, transform them in some way and
    // echo them back out
    boost::copy(
        getlines(std::cin)
            | boost::adaptors::filtered(some_pred)
            | boost::adaptors::transformed(some_func),
        std::ostream_iterator<std::string>(std::cout, "n"));
    

    That’s strong stuff. I shudder to think what the equivalent code would look like with straight iterators and STL algorithms.

    But what if you just want to read a single line? Doesn’t the new getlines hurt you for this simple usage scenario? Nope! All we need is one perfectly general function that returns the first element of a range. Let’s call it front:

    using std::begin;
    
    // return the front of any range    
    template<typename Range>
    auto front(Range && rng)
        -> decltype(boost::make_optional(*begin(rng)))
    {
        for(auto x : rng)
            return x;
        return boost::none;
    }
    

    Since a range might be empty, we need to return an optional. Now you can read a single line from an istream like this:

    if(auto s = front(getlines(std::cin)))
        use_line(*s);
    

    Compare this to the original and I think you’ll see it’s no worse:

    std::string str;
    if(std::getline(std::cin, str))
        use_line(str);
    

    Stateful Algorithms

    So have we completely addressed all of Andrei’s concerns with getline? Yes and no. Certainly we’ve fixed getline, but Andrei’s point was bigger. He was showing that you can’t just blindly pass and return by value, hoping that move semantics will magically make your programs faster. And that’s a valid point. I can’t say anything that changes that fact.

    I think getline is a curious example because what looks at first blush like a pure out parameter is, in fact, an in/out parameter; on the way in, getline uses the passed-in buffer’s capacity to make it more efficient. This puts getline into a large class of algorithms that work better when they have a chance to cache or precompute something. And I can say something about that.

    If your algorithm needs a cache or a precomputed data structure, then your algorithms are inherently stateful. One option is to pass the state in every time, as getline does. A better option is to encapsulate the state in some object that implements the algorithm. In our case, the state was the buffer and the object was the range. To take another case, Boyer-Moore search is faster than strstr because it precomputes stuff. In the Boost implementation, boyer_moore is a stateful function object that keeps its precomputed part private.

    Summary

    Here are the key take-aways:

    • If your algorithm runs faster with a cache or a precomputed data structure, encapsulate the state in an object that implements the algorithm, rather than forcing your users to pass the state in.
    • API design must be guided by the expected usage scenarios of the API, and also the common idioms of modern C++11.
    • Ranges are a powerful abstraction because operations on them compose.
    • Boost.Iterator and Boost.Range greatly simplify the job of implementing custom ranges.

    Thanks for reading!

    x
  • Universal References and the Copy Constructor

    At the most recent NWCPP meeting in Redmond, WA, the always-entertaining Scott Meyers shared his latest insights about so-called “universal references” and their pitfalls. In particular, he was warning about the hazards of overloading on universal references. His advice was good, I thought, but missed some important corner cases about the interactions between universal references and copy constructors. In this article, I show what the special problems are and some ways to avoid them.

    Universal References

    But first, a refresher. What does Scott mean by “universal references”? He basically means this:

    template<typename T>
    void foo( T && t )
    {
        // "T &&" is a UNIVERSAL REFERENCE
    }
    

    In the above code, T && is what Scott calls a universal reference. In C++, there are lvalue references and rvalue references to distinguish between references to named and unnamed objects (roughly). The rules of template type deduction and reference collapsing conspire to make the above simple syntax have the seemingly magical property that T && can bind to anything, rvalue or lvalue. Let me repeat that, with emphasis: T && here can be either an lvalue reference or an rvalue reference. Consider:

    int i = 42;
    foo( i );  // lvalue, "T &&" deduced to be "int &"
    foo( 42 ); // rvalue, "T &&" deduced to be "int &&"
    

    See? foo can be called with either lvalues or rvalues, and the deduced type of T && reflects that. (Perfect forwarding relies on that property of universal references.) It’s that somewhat magical property that led Scott to coin the phrase “universal references.”

    Avoid Overloading on Universal References

    Scott’s advice is simple and sound: avoid overloading on universal references. By which he means, don’t do this:

    template<typename T>
    void foo( T const & t )
      {/*...*/}
    
    template<typename T>
    void foo( T && t )
      {/*...*/}
    

    In the code above, the author presumably wanted all lvalues to go to the first and all rvalues to go to the second. But that’s not what happens. What happens is this: const lvalues most certainly go to the first, and all rvalues most certainly go to the second, but non-const lvalues also go to the second. See, the second overload takes a universal reference, which, as you recall, binds to anything. As we saw above, T && could deduce to int &. If we pass a non-const integer, the second overload which can take an int & is a better match than the first which can take an int const & at best.

    Sadly, this is not some esoteric problem you can safely forget about. I’ve seen people make this mistake in the real world, and in one case, the code was accidentally moving from an lvalue as a result, leaving a ticking time bomb in production code.

    Scott’s advice is to instead write one function, the one taking the universal reference, and internally dispatch to one of two helpers. One sensible way to dispatch might be to use the std::is_lvalue_reference trait, like so:

    template<typename T>
    void foo_impl( T && t, std::true_type )
      {/* LVALUES HERE */}
    
    template<typename T>
    void foo_impl( T && t, std::false_type )
      {/* RVALUES HERE */}
    
    template<typename T>
    void foo( T && t )
    {
        foo_impl( std::forward<T>(t),
                  std::is_lvalue_reference<T>() );
    }
    

    Although verbose, I agree that this is a fairly straightforward way of handling this particular problem.

    Special Problems with the Special Member Functions

    This is all well and good. We can chalk this up as Yet Another C++ Quirk, learn to recognize the quicksand and avoid stepping in it. If only we could get off so easily! The problem comes from the copy constructor. C++ has rules for when it gets generated automatically. Ordinarily that’s a boon that saves users from typing repetitive boilerplate, but sometimes it can be surprising.

    Consider a simple wrapper object that holds some object of type T:

    template<typename T>
    struct wrapper
    {
        T value;
        wrapper( T const & v )
          : value( v ) {}
    };
    

    That’s dandy. But this is 2013 and we have move semantics and perfect forwarding now, so we want to change our wrapper to take advantage of them. To get perfect forwarding, we have to use universal references, so we do this:

    template<typename T>
    struct wrapper
    {
        T value;
        template<typename U>
        wrapper( U && u )
          : value( std::forward<U>(u) ) {}
    };
    
    // The array is perfectly forwarded to the
    // string constructor.
    wrapper<std::string> str("hello world");
    

    This is kosher, right? Sadly not, because in some circumstances, the compiler will try to use the above constructor as a copy constructor, and that’s not good.

    But wait! you say. A template can’t be used as a copy constructor! If that’s what you’re thinking, you’re almost right. The truth is — and Scott Meyers correctly points this out — that the compiler refuses to use a template to generate a copy constructor. The difference is subtle but crucially important, as we’ll see.

    When the compiler sees this:

    // Copy the wrapper
    wrapper<std::string> str2 = str;
    

    … it looks at the wrapper class and, seeing no copy constructor (and refusing to use the template to generate one), it automatically generates a new one:

    template<typename T>
    struct wrapper
    {
        T value;
        template<typename U>
        wrapper( U && u )
          : value( std::forward<U>(u) ) {}
        // THIS IS COMPILER-GENERATED:
        wrapper( wrapper const & that )
          : value( that.value ) {}
    };
    

    What happens next is truly bizarre. The compiler, after generating a constructor to use, then decides not to use it. Say what?! That’s right. Overload resolution now kicks in. Recall that the code of interest is:

    wrapper<std::string> str2 = str;
    

    str is a non-const lvalue of type wrapper<std::string>. There are two constructors to choose from. The compiler-generated one is certainly viable, but the first is a better match. Why? Because U && can be deduced as wrapper<std::string> &. Although a template is never used to generate a copy constructor, a template may end up being used anyway if overload resolution selects it. In short, we end up forwarding a wrapper object to the std::string constructor, and we fail. Oops. Had str had been const, then the other constructor would have been selected and it would have worked. Schitzo!

    Variadic templates are another fly in this ointment. Consider the following:

    template<typename ... Ts>
    struct tuple
    {
        // Whoops, this can be a copy constructor!
        template<typename ... Us>
        tuple( Us &&... us ) : /* etc... */
    };
    

    The intent here is to define a tuple type with a constructor that perfectly forwards all its argument. And it can be used that way, but (hold on to your hats) it can also be used as a copy constructor! In that case, Us &&... deduces to tuple &. Whoa.

    The Solution

    So what’s a well-intentioned C++ programmer to do? What if you really, really want a constructor that perfectly forwards one argument? There are a bunch of “fixes,” but most have their own problems. Here is what I’ve found to work the most reliably.

    // write this once and put it somewhere you can
    // reuse it
    template<typename A, typename B>
    using disable_if_same_or_derived =
        typename std::enable_if<
            !std::is_base_of<A,typename
                 std::remove_reference<B>::type
            >::value
        >::type;
    
    template<typename T>
    struct wrapper
    {
        T value;
        template<typename U, typename X =
            disable_if_same_or_derived<wrapper,U>>
        wrapper( U && u )
          : value( std::forward<U>(u) )
        {}
    };
    

    There’s a lot going on there, but the gist of it is this: we use metaprogramming to disable the constructor if the parameter is a wrapper. In fact, the constructor is disabled for types derived from wrapper, too. Why? Because it preserves the expected semantics of C++. Consider:

    struct A {};
    struct B : A {};
    B b;
    A a = b;
    

    There’s nothing wrong with doing that. B inherits from A, so we can construct an A from a B and we get slicing behavior. If A were to acquire one of these troublesome universal constructors we’ve been discussing, it would no longer slice. The universal constructor would get called instead, and we’d get some new, exciting, and probably wrong behavior.

    Summary

    In short, take Scott’s advice and don’t overload on universal references. But if you are writing a universal constructor (that is, a single-argument constructor that takes a universal reference), constrain the template so that it can’t be used as a copy constructor. You’ll be sorry if you don’t!

  • F-Algebras and C++

    “I think F-algebras would be useful in Proto.” That’s how Bartosz Milewski planted the seed in my head that has now matured into this blog post. Bartosz had been writing a blog post about F-algebras, and in a bid to get me to review it, he dangled the Proto carrot. I bit.

    In F-algebras, the evaluation of an expression is separate from the recursion. The algebra specifies how expression trees of one level are evaluated, and the rest is handled by a catamorphism, which is written once and shared across all algebras. I’m a lazy programmer. I’m also a sucker for some pretty math. So I was hooked.

    Bartosz’s code is in Haskell, so my first step was to port it to C++. The rest of this post presents my port of the F-algebra code to C++11. You’ll want to first read Bartosz’ post, which is where the real meat is. When it all makes sense, come back here and see how this all maps to C++.

    Disclaimer: This is not intended to be a readable introduction to F-algebras. For that read Bartosz’ blog.

    The ExprF type in Haskell

    Bartosz uses a simple expression tree as his driving example. It looks like this:

    data ExprF a = Const Int
                 | Add a a
                 | Mul a a
    
    type Expr = Fix ExprF
    

    Of note is the fact that ExprF is not recursive; that is, ExprF isn’t implemented in terms of itself. Yet he claims this is a tree data structure, and trees are recursive. What gives?

    The answer is that the recursion is provided externally by a type constructor called Fix. If ExprF Int is a tree of one level, and ExprF (ExprF Int) is a tree of two levels, then Fix ExprF is a tree of infinite levels. How do you know when you’ve reached infinity? When one more gets you back where you started. That’s a fixed point, and Fix is a fixed point. It fakes up an infinite number of applications of its parameter F. For any type constructor F, the type Fix F is such that another application of F gets you back to where you started. Let’s look at how Fix is defined.

    The Fix Type

    Fix lets you create recursive data structures from a non-recursive shell. Here’s the Haskell. I include the unFix function here as well.

    newtype Fix f = Fx (f (Fix f))
    
    unFix :: Fix f -> f (Fix f)
    unFix (Fx x) = x
    

    Here, f is a unary type constructor, and Fx is a data constructor that takes an f (Fix f) and returns a Fix f. In C++, a unary type constructor is a class template that takes one parameter. Fix, then, is a template that takes a unary class template as a parameter, and Fx is a function that returns a Fix:

    template<template<typename> class F>
    struct Fix
      : F<Fix<F>>
    {
        explicit Fix(F<Fix<F>> f)
          : F<Fix<F>>(f)
        {}
    };
    
    template<template<typename> class F>
    Fix<F> Fx(F<Fix<F>> f)
    {
        return Fix<F>{f};
    }
    
    template<template<typename> class F>
    F<Fix<F>> unFix(Fix<F> f)
    {
        return f;
    }    
    

    From the C++ we can see that Fix really is a fixed point. Fix<F> inherits from F<Fix<F>>. Inheritance is an IS-A relationship, so a Fix<F> really is a F<Fix<F>>. (Whether you consider the inverse to be true — that is, whether a F<Fix<F>> is a Fix<F> — depends on how literal-minded you are. For my purposes, the Fx function makes it so.)

    Back to Haskell. With Bartosz’ definition of ExprF and Fix, we can create expression trees of arbitrary depth as with the following somewhat verbose example:

    testExpr = Fx $ 
                   (Fx $ (Fx $ Const 2) `Add` (Fx $ Const 3))
                    `Mul` (Fx $ Const 4)
    

    But what is the best way to express ExprF in C++? That’s not obvious.

    The ExprF type in C++

    Let’s look again at the definition of ExprF in Haskell.

    data ExprF a = Const Int
                 | Add a a
                 | Mul a a
    

    We can read this as follows: if someone gives us an ExprF a, it could contain either a Const Int, an Add a a, or a Mul a a. This either/or spiel sounds a lot like a union. We could hack something like this up with C++11’s unrestricted unions, but Boost gives us a nicer way: boost::variant. Without further ado, here’s how I ported ExprF to C++:

    struct Const_
    {
        int value;
    };
    
    template<typename A>
    struct Add_
    {
        A left;
        A right;
    };
    
    template<typename A>
    struct Mul_
    {
        A left;
        A right;
    };
    
    template<typename A>
    using ExprF_ =
        boost::variant<
            Const_
          , boost::recursive_wrapper<Add_<A> >
          , boost::recursive_wrapper<Mul_<A> >
        >;
    
    template<typename A>
    struct ExprF
      : ExprF_<A>
    {
        typedef ExprF<A> tag;
        ExprF(Const_ c) : ExprF_<A>(c) {}
        ExprF(Add_<A> c) : ExprF_<A>(c) {}
        ExprF(Mul_<A> c) : ExprF_<A>(c) {}
    };
    
    using Expr = Fix<ExprF>;
    

    This is verbose but mostly straightforward. But wait, what’s going on with boost::recursive_wrapper? Isn’t ExprF supposed to be non-recursive? Well yes, and technically, it still is. But once we start building trees, it is made recursive by Fix. In Haskell, recursive types are no problem. In C++ though, your struct S can’t have a member of type S. It can have a member of type S* though, and that’s essentially what boost::recursive_wrapper does for you under the covers.

    Some utility functions for constructing ExprF objects will come in handy later:

    template<typename A = Expr>
    ExprF<A> Const(int val) {return Const_{val};}
    
    template<typename A>
    ExprF<A> Add(A a, A b) {return Add_<A>{a, b};}
    
    template<typename A>
    ExprF<A> Mul(A a, A b) {return Mul_<A>{a, b};}
    

    The cata Function

    Recursion in your data types is done externally by Fix, and recursion in your algorithms is done externally by a very general function called a catamorphism, or cata. Bartosz’ derivation of the cata function is very interesting, and I encourage you to read it. The result is here:

    cata :: Functor f => (f a -> a) -> Fix f -> a
    cata alg o = alg . fmap (cata alg) . unFix o
    

    We read this, as we do all mathematical function compositions, from right to left. unFix o has the effect of unpacking one level of our recursive, fixed-point data structure. That yields a Functor that we can fmap over. Even without knowing how fmap is implemented for our type, we can see that it will be calling cata alg recursively. (It’s not clear at this point how the recursion ever ends. We’ll see that in a bit.)

    This is cata in C++. Short and sweet … almost.

    template<typename Alg, template<typename> class F>
    ???? cata(Alg alg, Fix<F> o)
    {
        using std::placeholders::_1;
        return alg(fmap(std::bind(&cata<Alg, F>, alg, _1),
                        unFix(o)));
    }
    

    In Haskell, when you pass one argument to a function that expects two, you get a function that takes one argument. Cool. What you get when you do that in C++ is a compiler error. 😛 So instead, I use the very handy std::bind. Lambdas are more fashionable, but hey I’m a bit old-fashioned.

    The only snag is when we try to declare the return type. cata returns whatever alg returns when passed a … what? Well, whatever fmap returns. But the type returned by fmap depends on a recursive call to cata, and we get stuck in a Catch-22 trying to compute it. What we can say about the return type of fmap is that it will be some instance of template F, but we don’t know which. So, I cheat:

    // A horrible hack for the purpose of computing
    // cata's return type. AnyF<F> stands in for a F<T>
    // when T is unknown.
    template<template<typename> class F>
    struct AnyF
    {
        template<typename T>
        operator F<T> &() const;
    };
    
    template<typename Alg, template<typename> class F>
    typename std::result_of<Alg(AnyF<F>)>::type
    cata(Alg alg, Fix<F> o)
    {
        using std::placeholders::_1;
        return alg(fmap(std::bind(&cata<Alg, F>, alg, _1),
                        unFix(o)));
    }
    

    I won’t dwell on the horribleness of this hack, why it works, and why sometimes it won’t. The less said the better.

    fmap

    If you’re a Haskeller, you know that fmap means Functors. (That’s the mathematical “Functor” with a capital “F”, which is probably different from the C++ thing you may be familiar with.) If you’re not a Haskeller, here’s the skinny: Given an instance of a class template F<A> and a function that maps from A to B, it gives you a F<B> by doing something. That something is different for every fmap-able type.

    Functor in Haskell is a type class. Type classes and instances are like concepts and concept maps in C++, if only we had them. So how should something like Haskell’s Functor type class be translated into C++? It’s an interesting question. For now, I make a simplifying assumption: all types modeling the “Functor” concept in C++ are implemented as a boost::variant. (Obviously, that’s the case for ExprF.)

    Here is fmap in C++:

    template<typename Fun, typename Tag>
    struct functor_visitor;
    
    template<typename Fun, typename Fa>
    typename
        functor_visitor<Fun, typename Fa::tag>::result_type
    fmap(Fun f, Fa fa)
    {
        return boost::apply_visitor(
            functor_visitor<Fun, typename Fa::tag>{f}, fa);
    }
    

    boost::apply_visitor is a simple wrapper that checks to see which slot is occupied in the variant and dispatches to the right handler in functor_visitor. That is where you put the fmap logic for your type. Here is how functor_visitor is implemented for ExprF:

    template<typename Fun, typename A>
    struct functor_visitor<Fun, ExprF<A>>
      : boost::static_visitor<
            ExprF<typename std::result_of<Fun(A)>::type>>
    {
        typedef typename std::result_of<Fun(A)>::type B;
    
        explicit functor_visitor(Fun f)
          : f_(f)
        {}
    
        ExprF<B> operator()(Const_ i) const
        {
            return Const<B>(i.value);
        }
    
        ExprF<B> operator()(Add_<A> e) const
        {
            return Add(f_(e.left), f_(e.right));
        }
    
        ExprF<B> operator()(Mul_<A> e) const
        {
            return Mul(f_(e.left), f_(e.right));
        }
    private:
        Fun f_;
    };
    

    So, fmap with a function and an ExprF<A> does one of three things depending on what’s in the ExprF. Each operator() overload handles one possible case, and they all return ExprF<B>, where B is what Fun returns when passed an A.

    Looking at cata, the function we’ll be fmap-ing over will be std::bind(&cata<Alg, F>, alg, _1). If the ExprF<A> contains an Add_ or a Mul_, then we end up recursively invoking cata. But when we reach a Const_, we don’t recurse. That’s good, because otherwise cata would never return!

    F-algebra

    So what is alg? That’s the best part: you decide! It’s an algebra; a way build expressions out of symbols and evaluate them. Below is a simple algebra in Haskell that will cause cata to evaluate the expression tree in a meaningful way:

    alg :: ExprF Int -> Int
    
    alg (Const i)   = i
    alg (x `Add` y) = x + y
    alg (x `Mul` y) = x * y
    

    This is what it looks like in C++:

    struct alg_visitor
      : boost::static_visitor<int>
    {
        int operator()(Const_ i) const
        {
            return i.value;
        }
    
        int operator()(Add_<int> e) const
        {
            return e.left + e.right;
        }
    
        int operator()(Mul_<int> e) const
        {
            return e.left * e.right;
        }
    };
    
    int alg(ExprF<int> e)
    {
        return boost::apply_visitor(alg_visitor{}, e);
    }
    

    And here’s an example of cata and alg evaluating an expression tree:

    // (2+3)*4 == 20
    Expr testExpr =
        Fx(Mul(
            Fx(Add(
                Fx(Const(2)),
                Fx(Const(3))
            )),
            Fx(Const(4))
        ));
    int z = cata(alg, testExpr);
    std::cout << z << std::endl;
    

    This prints 20 like you might expect. You could easily define other algebras that would cause the same expression tree to be evaluated in different ways.

    Summary

    Notice that alg is not recursive. Something really cool has happened here. We only had to specify how to handle trees of one level, and for free we’re able to evaluate trees of any depth. Everything else is handled by Fix and cata.

    Why do I care, besides the fact that it’s fun and cool? Boost.Proto, my library for building embedded domain-specific languages in C++, has a little DSL for specifying how expressions should be evaluated. In that DSL, the tree traversal logic is mixed in with the rest of the algorithm. This makes it tricky to write Proto algorithms. If only there were a way to get recursive evaluation for free while only specifying the interesting bits … Hence my interest in F-algebras.

    Bartosz and I have been discussing how to extend this to work with my use cases. We’ve found that, when combined with the State monad, the cata function can be made to do folds, an important part of many expression evaluation schemes. But perhaps I’ll save that for later.

    You can find this code in a slightly generalized form at my github repo. There you can also find my implementation of the State monad.

  • Best Professional Advice I Ever Got

    This is the story of the best piece of professional advice I ever got, and how it affected my career. I think it’s good advice, and I’ve never stopped thinking about it, so I thought it was time to share.

    The Advice

    It was 1996 and I was just starting work at my first job outside college. The company: Microsoft. The product: Windows 2000. The team was Base Test, and my boss was a guy named Terry Lahman, a lean mustachioed Dad-type who really cared about the product and his employees. I was nervous and green and didn’t have a clue what I was doing. Eager to please, I did everything Terry ever asked of me, as best as a new college grad could.

    One day he came into my office, and this is what he said:

    Eric, every now and then I’m going to come into your office and ask you, “What are you working on that I don’t know about?” You should always have something to tell me.

    I remember being surprised, which is probably why it stuck. I thought he’d be upset if he found out I was “wasting” time on outside projects. But here he was, telling me to do just that.

    The Results

    After that, I started taking on little side projects. I learned fast. A dislike of Perl and a love of C++ led me to write a C++ regular expression engine called GRETA. It had little to do with my job, but that’s OK. Terry always took a keen interest in my projects, and they never interfered with my work. My passion for code grew.

    As luck would have it, my little regex engine became popular within Microsoft, and several groups started using it. Around that time, the C++ world was abuzz with talk about TR1, a set of planned extensions to the standard library. They were looking for C++ regex engines, so I got involved in the C++ standardization effort (an involvement that continues to this day).

    Through my interactions with the standardization committee, I met a lot of talented and smart people. I also came to hear about Boost, a collection of open source C++ libraries. Eventually, my path crossed that of Dave Abrahams, a co-founder of Boost, and he and I became friends. When I finally decided to leave Microsoft, Dave took me on as a sub-contractor at BoostPro Computing.

    During this time, my involvement in Boost grew. No matter what I had going on work-wise, I always had side-projects, as if Terry might walk into my office at any time. I wrote a new regex engine called Boost.Xpressive. As part of that work, I wrote a library called Boost.Proto for building embedded domain-specific languages. People started using my code and wanting my help on their projects.

    Now I work for myself. Clients find me through my open source contributions, which I always make time for. I have never forgotten that day Terry encouraged me in just the right way.

    Be Passionate

    To me, Terry’s advice is about initiative and passion. Don’t wait for someone to tell you what to do. Just do it. Experiment. Play. You’ll find your passion, and you’ll surprise and delight your boss, your clients, and yourself.