C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Integer overflow arithmetic

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Sat, 17 Feb 2024 11:49:33 +0000

>I don't really get the following case in your code:
> if constexpr (sizeof(T) >= sizeof(U)) return false;

Ok, the statement is phrased in the negative, i.e. If I can represent a value in its destination type then the result is false, meaning that casting this type doesn't change the meaning of the value.
In this branch std::is_signed_v<T> == std::is_signed_v<U> is true, i.e. that they are both signed or both unsigned
Then this compares the storage size, and T is the type we are converting too, if the type we are converting too has a greater or equal storage size and it has the same "signed'ness" , then I can always convert it without affecting the representation.

Thus explaining
> Why would T not be able to represent x in the event that T is larger.
> Doesn't this imply that "would_cast_modify<long long>(0)" is false?

false means you can represent.


> In the case where the signedness is left unchanged by the cast, you can probably do:
> static_cast<From>(static_cast<To>(x)) == x
> This simply checks whether the roundtrip conversion preserves the value.

Note we are not checking for round-trip convertible. Take the following example:

constexpr int8_t test_case = -1;
constexpr uint32_t converted_case = static_cast<uint32_t>(test_case);
constexpr int8_t round_trip_case = static_cast<int8_t>(converted_case);
static_assert(test_case == round_trip_case);

This is round-trip convertible but it is not one-way convertible as converted_case cannot represent -1.

Received on 2024-02-17 11:49:36