When using a ternary operator within list initialization, what causes the implicit conversion of int to unsigned int (and similarly for long long) but not short to unsigned short (and similarly for char).
Specifically, I am surprised that the i32v2 function compiles fine whereas the others do not:
unsigned short f16(unsigned short x);
unsigned int f32(unsigned int x);
void i16(short value) {
unsigned short encoded{value}; // narrowing, makes sense
}
void i32(int value) {
unsigned int encoded{value}; // narrowing, makes sense
}
void i16v2(short value) {
unsigned short encoded{false ? value : f16(value)}; // narrowing, makes sense
}
void i32v2(int value) {
unsigned int encoded{false ? value : f32(value)}; // not narrowing, huh?
}
Complete example here: https://godbolt.org/z/fVTcrr
I am guessing the ternary operator implicitly converts int to unsigned int but I do not understand why it is unable to convert short to unsigned short similarly.
I would expect, if it was possible for int, then the ternary operator should also be able to convert any of the other signed types to the unsigned when possible:
If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n where n is the number of bits used to represent the destination type.
(https://en.cppreference.com/w/cpp/language/implicit_conversion)
Can someone explain this behavior, and if possible, reference the standard or applicable cppreference page?
Aucun commentaire:
Enregistrer un commentaire