C++11 formalized the notion of a narrowing conversion, and disallowed using one at the top level in list-initialization.
I am wondering whether, given two types T
and U
, it is possible for it to be implementation-defined whether a conversion from T
to U
is narrowing. According to my reading of the standard, this is the case. Here is my reasoning:
- According to dcl.init.list (8.5.4) paragraph 7, one way a conversion can be narrowing is if it's an implicit conversion "from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type".
- Consider an implicit conversion from
unsigned int
tolong
. - Regarding the relative sizes of
int
andlong
, C++ requires only thatsizeof(int) <= sizeof(long)
. - Consider an implementation A, where
sizeof(int) == sizeof(long)
. On this implementation,long
cannot represent all the values ofunsigned int
, so the conversion would be narrowing. - Consider an implementation B, where
sizeof(int) < sizeof(long)
. On this implementation,long
can represent all the values ofunsigned int
, so the conversion would not be narrowing.
Am I correct in my analysis that it can be implementation-defined whether a conversion is narrowing? Is this desirable?
int i{long(5)}
is never a narrowing conversion.5
is a literal, and its value will fit in anint
, so the compiler is required to allow it. – Disinherit