在表达式bool<<整数,是bool提升为int,还是与整数相同的类型?

时间:2015-09-26 18:58:56

标签: c++ implicit-conversion integer-promotion

请考虑以下代码:

// 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);

已定义或未定义的行为?

1 个答案:

答案 0 :(得分:3)

来自[expr.shift]:

  

操作数应为整数或无范围的枚举类型,并执行整体促销。结果的类型是提升的左操作数的类型。

来自[conv.prom]:

  

bool类型的prvalue可以转换为int类型的prvalue,false变为零,true成为一个。

bool上的整体推广会产生int。因此true << (any integral type)的结果类型为int。整体提升后的true << static_cast<char>(9)1 << 9相同,512定义为* { box-sizing:border-box; /* Use browser prefixes if u want support for other browsers */ }