在表达式 bool << integer 中,bool 是提升为 int,还是提升为与整数相同的类型?
In the expression bool << integer, is bool promoted to int, or to the same type as the integer?
考虑以下代码:
// E1 << E2 with E1 bool, and E2 an integer
true << static_cast<char>(1);
true << static_cast<short int>(1);
true << static_cast<int>(1);
true << static_cast<unsigned int>(1);
true << static_cast<long long int>(1);
true << static_cast<long long unsigned int>(1);
运算时,E1
是提升为与E2
同类型,还是先提升为int
再提升为std::common_type<E1, E2>::type
?
换句话说就是:
true << static_cast<char>(9);
已定义或未定义的行为?
来自[expr.shift]:
The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.
来自[conv.prom]:
A prvalue of type bool
can be converted to a prvalue of type int
, with false
becoming zero and true
becoming one.
bool
的积分提升产生 int
。所以true << (any integral type)
的结果类型是int
。积分提升后的true << static_cast<char>(9)
等同于1 << 9
,明确定义为512
。
考虑以下代码:
// E1 << E2 with E1 bool, and E2 an integer
true << static_cast<char>(1);
true << static_cast<short int>(1);
true << static_cast<int>(1);
true << static_cast<unsigned int>(1);
true << static_cast<long long int>(1);
true << static_cast<long long unsigned int>(1);
运算时,E1
是提升为与E2
同类型,还是先提升为int
再提升为std::common_type<E1, E2>::type
?
换句话说就是:
true << static_cast<char>(9);
已定义或未定义的行为?
来自[expr.shift]:
The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.
来自[conv.prom]:
A prvalue of type
bool
can be converted to a prvalue of typeint
, withfalse
becoming zero andtrue
becoming one.
bool
的积分提升产生 int
。所以true << (any integral type)
的结果类型是int
。积分提升后的true << static_cast<char>(9)
等同于1 << 9
,明确定义为512
。