Defined conversion narrowing?

C ++ 11 formalized the concept of narrowing down a conversion and forbade the use of one at the top level in list initialization.

I am wondering if it is possible for two types of T and U define an implementation if the restriction occurs from T to U According to my reading of the standard, it is. Here are my thoughts:

  • In accordance with clause 7 of dcl.init.list (8.5.4), one of the methods of narrowing a conversion may be narrowing if it is an implicit conversion "from an integer type or from an type of an enumerated enumeration to an integer type that cannot represent all the values โ€‹โ€‹of the original type" .
  • Consider the implicit conversion from unsigned int to long .
  • As for the relative sizes of int and long , for C ++ only sizeof(int) <= sizeof(long) is required.
  • Consider an implementation of A, where sizeof(int) == sizeof(long) . In this implementation, long cannot represent all unsigned int values, so the conversion will narrow.
  • Consider an implementation of B, where sizeof(int) < sizeof(long) . In this implementation, long can represent all unsigned int values, so the conversion will not narrow down.

Is it correct in my analysis that this can be determined by the implementation, is the transformation narrowing? Is this desirable?

+6
source share
1 answer

I would prefer that the definition of narrowing be defined on the types themselves. So that int i{long(non_constant_expression)} never allowed to compile. A simple reason: either you do not need a large range, then you must use int first and foremost, or you really want to โ€œcutโ€, which seems to be a rather rare case for me to require an explicit type of transform or cast. To answer the first question: Implementation is defined.

But honestly, I almost never use these raw types, just size_t , int32_t , uint16_t , etc., and this automatically solves the problem. ( uint16_t {uint8_t()} always narrows, uint16_t{uint16_t()} never.) You just need to thoughtfully convert size_t to something else, but that's always the case.

+4
source

All Articles