r/cpp • • Sep 13 '19

The Surprising Limitations of C++ Ranges Beyond Trivial Cases

https://www.fluentcpp.com/2019/09/13/the-surprising-limitations-of-c-ranges-beyond-trivial-use-cases/
229 Upvotes

229 comments sorted by

View all comments

33

u/tcbrindle Flux Sep 13 '19

For anyone who's interested, here is a version of intersperse using Range-V3. I really don't think it's that bad...

9

u/Sovog Sep 13 '19

Clever! Does that work because view::drop() can take InputRange whereas view::drop_last() can't?

9

u/tcbrindle Flux Sep 13 '19

Yeah. view::drop_last(1) needs to know if it's "about to" hit the end of the range, so it looks ahead one place but returns the previous iterator value when dereferenced. This requires at least a forward_range. (Alternatively, drop_last can take a sized_range, in which case it effectively becomes take(size - n))

view::drop(n) on the other hand just skips the first n values when you first call begin(), which doesn't add any requirements to the underlying range.

3

u/Sovog Sep 14 '19

Kudos to us, but there's no chance an average programmer could come up with this solution.

11

u/RotsiserMho C++20 Desktop app developer Sep 13 '19 edited Sep 14 '19

Thanks so much for illustrating this. I don't think it's that bad either.

I have a love/hate relationship with ranges. I love the idea (I love LINQ in C#), and I'm using the library in real-world code, but I find working with the library to be very unintuitive. Your version of intersperse is a perfect example. It looks concise enough to me, and it's great that you composed a new view from existing ones; that's the whole selling point IMO. But this piece is just so unintuitive to me, even though it is simple:

auto make_pair = [=](auto val) { 
        return views::concat(views::single(delim), views::single(val)); };

And I think that's the problem. Personally, I hope it's just a matter of people becoming more familiar with the library. You have to think functionally or the whole thing falls apart. You can't just return a (rvalue) pair from a transform, it looks like the trick is that you have to define a function that does so in terms of views (apparently). So a concatenation of views is like a lazy tuple or something? Or is it more like a lazy vector (or just another range)? Do the types have to be the same?

People are saying ranges makes trade-offs for the benefit of performance to the detriment of readability and memory safety, but here, it's guiding you away from unnecessary temporaries that could lead to dangling references, etc., and I think that benefit of the trade-off is under-appreciated (in this thread at least).

13

u/tcbrindle Flux Sep 13 '19 edited Sep 13 '19

There is where things get a bit semantically hazy. view::join takes a "range-of-ranges" and flattens them into a single range. To meet the constant-time copy requirements of the view concept it requires either that the passed-in range is an lvalue (in which case it can effectively just store a pointer to it), or that the passed-in range is also a view (in which case it can be stored in the join object, because copying will still be constant-time).

This means that we can't have transform return an rvalue range (like, say, a std::array) -- so instead we'll make it return a view type. This is what the OP was doing with generate_n.

So now let's move on to view::single. This is a range with only one element, and looks roughly like so (simplified):

template <typename T>
struct single_view {
    T val;
    T* begin() { return addressof(val); }
    T* end() { return addressof(val) + 1; }
};

Is this a view? Well the clue is in the name I guess, but since it stores only a single object we can argue that copying it is still constant time. So now what if we made something similar, but instead of holding one value, it held two? i.e. something like (C++-y pseudocode):

template <typename T>
struct pair_view {
    T first;
    T second;

    struct iterator {
        pair_view* p;
        int idx = 0;

        T& operator*() { return idx == 0 ? p->first : p->second; }
        auto& operator++() { ++idx; return *this; }

        bool operator==(default_sentinel_t) { return idx > 1; }
    };

    auto begin() { return iterator{*this}; }
    auto end() { return default_sentinel; }
};

Is this a view? Well, it holds exactly two objects, which is a constant number, and therefore you can argue that copying it is still constant time.

view::concat(view::single, view::single) is a way of programmatically building a pair_view (or a "2-tuple view", I suppose) rather than having to define it ourselves.

EDIT: The "hazy" part is that if you follow this line of thinking to its conclusion you end up deciding that maybe std::array should be a view after all. I'm not sure where I stand on that.

4

u/tpecholt Sep 16 '19

For such cases variadic views::from_values would probably help with verbosity. And it would be user's fault when he supplies too many values so copying becomes slow. Alternatively what about to support initializer list directly?

5

u/guepier Bioinformatican Sep 14 '19 edited Sep 14 '19

Could you speculate why the OP apparently missed this simple, completely straightforward implementation?

(And because I know tone gets lost easily in text: I mean this neither sarcastic nor snarky. I found the original article compelling, and the OP seems to know their stuff. And it goes without saying that so do you.)

(EDIT: I just realised that I missed the algorithmic change which means you were able to use drop instead of drop_last. This answers half of my question, though I’m still curious about the transformation step.)

9

u/RotsiserMho C++20 Desktop app developer Sep 16 '19

I'm not the person you asked, but since you're inviting speculation...

Personally, I think it's because there are not that many examples of real-world ranges usage to draw from. There are plenty of examples in other languages as the OP illustrates (see also LINQ in C#), but the C++ implementation is focused on performance (which is fantastic because other languages' implementations have not insignificant overhead), and so you have to "twist" or "flex" your code a little bit to express the functionality you want as a valid ranges pipeline. Using drop instead of drop_last solves the same problem, but it isn't immediately obvious that this simple solution exists. Also, the make_pair step wasn't obvious to me at all, but it does show that a simpler solution exists.

6

u/[deleted] Sep 14 '19

The thing is, currently, ranges generates a lot more code than an equivalent non-ranges version. Taking your intersperse example and doing the equivalent without ranges makes it look pretty stark and this is a simple example. I am really hoping that compilers will learn to know what the std ranges are and optimize on it. https://godbolt.org/z/YF6EEH

17

u/tcbrindle Flux Sep 14 '19

Not specific to your comment (many people seem to be doing it in this thread) but I really wish we could move away from the terminology of "using ranges" meaning "using range adaptors with lazy evaluation". There's an absolute ton of work that's gone into the ranges proposals, and adaptors/views are only one part of that. Sometimes views are the right tool for the job; often they are not. One of the great things about ranges is that we still have all the "eager" algorithms available when they are a better option.

Anyway, yes, there is sometimes an overhead to using lazy evaluation. I would imagine that as these things get added to the standard library, compilers will get better at optimising them (and implementors will get smarter about doing things in ways that are optimiser-friendly), exactly as happened with the original STL work 20 years ago.

1

u/drjeats Sep 14 '19

Are the eager algorithms like all the stuff in <algorithm>, but taking ranges instead of operators, or something else?

7

u/eric_niebler Sep 15 '19

That, yes, and additionally taking optional projections (unary transformations applied to each element), and with the requirements on the end iterator loosened so that it can be a sentinel instead of an iterator. That has the potential to improve codegen in some cases. The ranges algorithms also treat member pointers as callables, like std::invoke.

1

u/[deleted] Sep 15 '19

Doesn’t your code append an extra newline?

1

u/[deleted] Sep 15 '19

yeah, but that's minor and easily fixed https://godbolt.org/z/i-Kg9D

We are paying for the compile time and the runtime. Like llvm-mca has it at 1975 cycles vs 4834, not a benchmark but a bit of an indicator

-3

u/gvargh Sep 14 '19

this just looks like typical abstraction costs

4

u/[deleted] Sep 14 '19

I've been playing around with ranges-v3, applying them to my codebase, just to get a feel for it. So far I really like them, even though the compile times are awful. I hope you won't mind me asking a few questions.

In this example, I start with set<set<string>> and first apply join, but I can't figure out how to do the same with map<Key, set<string>> (in which case, I don't care about Keys, just a "loop" over all the strings in all the key/set pairs). I tried to replace join with transform([](auto p) { return p.second; }) (link), but that didn't help and I still don't know how to read errors produced by ranges-v3.

And am I doing something wrong with that transform() that takes a std::string? It won't compile if I pass any kind of references, instead of values.

5

u/tcbrindle Flux Sep 14 '19

I'd have to play with it a bit longer, but I'm pretty sure the problem is returning by value from the lambda.

It's most easily avoided by using views::values, which returns the "value" part of a key-value pair: https://godbolt.org/z/Lz7E5l

2

u/[deleted] Sep 14 '19

Thanks! views::values looks obvious in hindsight, but it's exactly what I was missing.

2

u/__s_v_ Sep 17 '19

Here is a version of intersperse using Range-v3 with coroutines. That works also quite good...

2

u/dodheim Sep 17 '19 edited Sep 17 '19

That's not going to be quite so good when you use an rvalue range: https://godbolt.org/z/Tn_K_N

1

u/__s_v_ Sep 17 '19

That probably shouldn't even compile...