我很好奇 C++ 中内置 bool
类型的某些行为。据我了解,std::common_type
使用隐式可转换性确定通用类型。我希望带有 bool
和另一种类型的表达式会导致 bool 转换为该类型。例如,我可以看到 bool + float
-> float
和 bool + double
-> double
。但是,bool + int8_t
-> int32_t
和 bool + int16_t
-> int32_t
。为什么会这样?
最佳答案
简答:积分推广。
在数值运算中,小整数类型(包括bool
、char
、unsigned char
、signed char
、 short
、unsigned short
等)如果所有可能的值都适合 int
,则提升为 int
,否则它们被提升为 unsigned int
。
在今天的大多数机器上,int32_t
与 int
相同。在 bool + int8_t
或 bool + int16_t
的情况下,两者都被提升为 int
。
关于c++ - 为什么bool和int8_t的普通类型在C++中是int32_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964431/