Jason Yu
Jason Yu

Reputation: 2038

Are there any simple ways to check whether a value cannot be safely presented by another type?

As titled.

For example, let's say we have an int8_t value "-10", I want to have a dynamic check (runtime value) in my program whether this exact integer value -10 can be safely held by a uint32_t variable after std::trunc. And in this case, since this is a negative value, so it CANNOT be held by an unsigned type. How can I do this in C++ code? Since if I use the normal comparison way, the implicit conversion would ruin the typing information like below. Is there any other simple way to do this?

  int8_t v = -10; 
  if (v <= std::numeric_limits<uint32_t>::max() &&
      v >= std::numeric_limits<uint32_t>::min()) {
    // It will be true here.
  }

I want to find a sound way to check whether the available value range of the target type can totally cover all the available values of the source type. Meaning after the explicit conversion, the result value should be exactly the same as the original one.

Upvotes: 4

Views: 1046

Answers (1)

phuclv
phuclv

Reputation: 41932

In C++20 you can use std::in_range

if constexpr (std::in_range<std::uint32_t>(v)) ...

See also Function checking if an integer type can fit a value of possibly different (integer) type


There's also intcmp to do comparisons yourself

if constexpr (std::cmp_greater(v, std::numeric_limits<uint32_t>::min())
           && std::cmp_less(v,    std::numeric_limits<uint32_t>::max()))
{
    ...
}

Upvotes: 9

Related Questions