C++ Logo

std-proposals

Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 8 Oct 2025 16:50:26 +0100
On Wed, 8 Oct 2025 at 16:23, Yexuan Xiao via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Why is it allowed to return a signed integer?
>

Because the function that it calls might 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.
>

For any range r with a r.size() or size(r) function that returns an
unsigned type, ranges::size(r) will also return an unsigned type.

If the container's r.size() returns a signed type, the problem is with that
container, not with ranges::size.


> 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,
>

You probably need to convert it to a specific type anyway.


> 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.
>

Not if you use std::cmp_equal, std::cmp_less etc.



> 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.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2025-10-08 15:50:43