Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 619
Jason Yu Avatar asked Jan 25 '23 08:01

Jason Yu


1 Answers

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

std::in_range<std::uint32_t>(v)

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

like image 118
phuclv Avatar answered Jan 26 '23 22:01

phuclv