C++ Logo

std-proposals

Advanced search

Re: [std-proposals] ranges::size should always return a unsigned integer

From: Robin Savonen Söderholm <robinsavonensoderholm_at_[hidden]>
Date: Wed, 8 Oct 2025 17:52:53 +0200
Incrementing iterators is actually most often done with their
`difference_type` rather than `size_type`, which tends to be signed.

I think the "usize()" function is easy enough to write yourself. The
difference from ssize() is that "std::size_t" as an unsigned type is
considered a mistake. We can't change that so the best we can do is make it
easy for users to migrate to signed "size".

// Robin

On Wed, Oct 8, 2025, 17:47 Jason McKesson via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Wed, Oct 8, 2025 at 11:23 AM Yexuan Xiao via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> >
> > Why is it allowed to return a signed integer? C++ users are accustomed
> to the fact that the size_type of containers is an unsigned integer, so the
> size of containers should also return an unsigned integer. sizes that
> return negative numbers are pathological and cannot be used. The current
> specification forces writers of generic algorithms to convert the result to
> unsigned on every call to ranges::size, which is something ranges::size
> should have taken care of. If they don't do this, the compiler will
> complain about signed and unsigned mismatches.
>
> Can you give an example of where that would happen? Presumably, the
> range's size_type should be used consistently. Incrementing iterators
> or using `operator[]` ought to use the same type as the return value
> of `size`. So as long as the writer of the generic code is writing it
> correctly, this shouldn't be a problem.
>
> That is, writers of generic code should use the type that gets
> returned, and use it consistently.
>
> > C++20 also added ranges::ssize, which always returns a signed integer.
> If generic algorithms prefer signed integers, they can use ranges::ssize.
> Therefore, it makes no sense for `ranges::size` to preserve the signedness
> of the return type of containers' size. Does C++ need ranges::usize? I
> believe the answer is clearly no. If C++ doesn't fix ranges::size in a
> timely manner, perhaps one day users will invent ranges::usize themselves
> and then tell others not to use ranges::size.
>
> Is there any evidence that this is likely? Besides your personal
> experience with it, is this a wide-spread concern?
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2025-10-08 15:53:08