ericniebler / stl2

LaTeX and Markdown source for the Ranges TS/STL2 and associated proposals
88 stars 8 forks source link

Bounded next and prev should also return the distance advanced #629

Open cjdb opened 5 years ago

cjdb commented 5 years ago

This is only really necessary for the bounded overloads, but a uniform interface would be nice.

Consider this code, which is from some pseudo-C++ I wrote while trying to design a cmcstl2 implementation for stride_view's operator++.

auto step = next(current_, stride, last_);
back_step_ = current_ == last_ ? distance(current_, last_) : 0;

If decltype(last_) models sized_sentinel_for<decltype(current_)>, then everything is honky-dory, since it's an O(1) computation. Otherwise, it's likely* to be a linear operation for operator++.

*citation needed

Since next is already doing all of the necessary work, it makes sense to me for it to also return the distance taken. We also get this information from the bounded advance.

Proposed resolution

[range.iter.op.next]

template<input_or_output_iterator I, sentinel_for<I> S>
  constexpr next_result<I,  iter_difference_t<I>>
    ranges::next(I x, S bound);

Effects: Equivalent to:

auto steps = ranges::advance(x, bound);
return {std::move(x), steps};
template<input_or_output_iterator I, sentinel_for<I> S>
  constexpr next_result<I,  iter_difference_t<I>>
    ranges::next(I x, iter_difference_t<I> n, S bound);

Effects: Equivalent to:

auto steps = ranges::advance(x, n, bound);
return {std::move(x), steps};

[range.iter.op.prev]

template<bidirectional_iterator I, sentinel_for<I> S>
  constexpr prev_result<I,  iter_difference_t<I>>
    ranges::prev(I x, iter_difference_t<I> n, S bound);

Effects: Equivalent to:

auto steps = ranges::advance(x, -n, bound);
return {std::move(x), steps};