C++ Logo

std-proposals

Advanced search

Re: Two small utility functions - as_signed, as_unsigned

From: Keenan Horrigan <friedkeenan_at_[hidden]>
Date: Sat, 09 Oct 2021 04:40:46 +0000
I think they'd be useful, in fact the ranges library has an exposition only "to-unsigned-like" function for range sizes. I'd prefer the naming of to_signed and to_unsigned however, as it's not referring to the same object like std::as_const. That naming would also line up with std::to_underlying.

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Saturday, October 9th, 2021 at 12:36 AM, Pavel Vazharov via Std-Proposals <std-proposals_at_[hidden]> wrote:

> Hi,
> What do you think of the usefulness of two such functions? Do they belong in the standard library?
>
> template <typename T>
> requires std::is_integral_v<T>
> constexpr auto as_signed(T v) noexcept
> {
> return static_cast<std::make_signed_t<T>>(v);
> }
>
> template <typename T>
> requires std::is_integral_v<T>
> constexpr auto as_unsigned(T v) noexcept
> {
> return static_cast<std::make_unsigned_t<T>>(v);
> }
> The thing is that the std::container::size() functions return an unsigned type but we often deal with signed types along with them and the compilers complain about comparison between these types when warnings are enabled. Such functions are useful in these situations, in my experience.
> Their naming is after std::as_const.
> Regards,
> Pavel

Received on 2021-10-08 23:40:52