When does std::is_convertible consider primitive types convertible?

1k Views Asked by At

Using std::is_convertible:

bool i2c = std::is_convertible<int, char>::value;
bool c2i = std::is_convertible<char, int>::value;
bool f2i = std::is_convertible<float, int>::value;

std::cout << std::boolalpha;
std::cout << i2c << '\n';  //prints true
std::cout << c2i << '\n';  //prints true
std::cout << f2i << '\n';  //prints true

I couldn't get why the output had to be true for all the above cases, when they appeared to be in-convertible (type conversions that can cause loss of precision). Or are we not supposed to compare the primitive types using std::is_convertible?

1

There are 1 best solutions below

0
On BEST ANSWER

The page linked states:

If the return statement in the imaginary function definition { return std::declval<From>(); } is well-formed, (that is, if std::declval<From>() can be converted using implicit conversion), provides the member constant value equal to true.

All of the types mentioned are implicitly convertible (although the compiler may issue a warning), ie:

float f = 0.8f
int i = f; // Legal implicit conversion.

Is perfectly legal and well formed. So std::is_convertible<float, int>::value will be true. The same holds for the remainder of the listed comparisons.