Title
Bit-fields and narrowing conversions
Status
open
Section
9.4.5 [dcl.init.list]
Submitter
Tim Song

Created on 2022-09-10.00:00:00 last changed 2 weeks ago

Messages

Date: 2022-09-10.07:48:26

Consider:

struct C {
  long long i : 8;
};

void f() {
  C x{1}, y{2};
  x.i <=> y.i; // error: narrowing conversion required (7.6.8 [expr.spaceship] bullet 4.1)
}

The rules for narrowing conversions in 9.4.5 [dcl.init.list] paragraph 7 consider only the source type, even though integral promotions can change the type of a bit-field to a smaller integer type without loss of value range according to 7.3.7 [conv.prom] paragraph 5:

A prvalue for an integral bit-field (11.4.10 [class.bit]) can be converted to a prvalue of type int if int can represent all the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can represent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the bit-field has enumeration type, it is treated as any other value of that type for promotion purposes.

There is implementation divergence in the handling of this example.

Possible resolution:

Change in 9.4.5 [dcl.init.list] bullet 7.4 as follows:

A narrowing conversion is 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, except where
    • the source is a bit-field whose width w is less than that of its type (or, for an enumeration type, its underlying type) and the target type can represent all the values of a hypothetical extended integer type with width w and with the same signedness as the original type or
    • the source is a constant expression whose value after integral promotions will fit into the target type, or
  • ...
History
Date User Action Args
2022-09-10 00:00:00admincreate