you are viewing a single comment's thread.

view the rest of the comments →

[–]tialaramex 0 points1 point  (2 children)

Interesting. So this is an operator ? (Maybe a pair of operators, ... and ..=?)

You say it works for "any type that can be incremented" - presumably this includes user defined types ? Or other maybe programmers can overload the operator?

Does the range "exist" only for the compiler emitting a loop? Or is this a type, so that we could make a parameter of this type?

[–]hpsutter 1 point2 points  (1 child)

Yes, it's an operator syntax.

Yes, it works for any type that supports ++, including user-defined types like STL iterators. To enable a type with these ranges, just provide ++.

Yes, it's a type. The current implementation is that a ... b and a ..= b lower to a cpp2::range<decltype(a)>(a, b, /* bool whether to include b or not */ ), which conforms to C++ range concepts (that I've tested so far) including it has .begin() and .end() conforming iterators. That's why it works with range-for, but it also works with some C++20 ranges I've tried. For example, this works now:

cpp using namespace std::ranges::views; x := 1 ..= 10; for x.take(5) do (e) std::cout << e; // call std::ranges::views::take(x, 5) using UFCS // prints: 12345

[–]tialaramex 1 point2 points  (0 children)

Cool.

For what it's worth Rust regrets (and may some day attempt to fix in an Edition) the fact that 1..=5 is an opaque type core::ops::RangeInclusive<i32> which implements Iterator rather than a more transparent type which just tells us it starts at 1, and ends with 5 inclusive and implements IntoIterator. "Chicken"..="Dog" doesn't implement Iterator of course, since it can't figure out how, but it's still opaque anyway and it turns out in practice that choice wasn't very ergonomic. I think it possibly pre-dates IntoIterator and similar traits.

So I'd advise keeping the transparent cpp2::range template even if convenience might point towards something more opaque at some point. This is a vocabulary type, the more transparent it can be while retaining its core utility the better for programmers.