为什么 common_type<long, unsigned long>::type = long long 不是?

Why isn't common_type<long, unsigned long>::type = long long?

本文关键字:long type gt 不是 为什么 lt common unsigned      更新时间:2023-10-16

common_type<long, unsigned long>::typeunsigned long,因为对于积分提升后的操作数,标准规定…

[…如果操作数为无符号整数类型,其排名大于或等于另一个操作数类型的秩有符号整数类型应转换为带的操作数类型无符号整型

不是说整型提升系统有问题,但如果有一个更大的符号整数类型,可以表示有符号操作数和无符号操作数的范围,就应该使用它。

我知道有些平台可能有long == long,在这种情况下,上述规则可以生效。但是如果一个更大的符号整型可用,不应该使用它吗?

首先,std::common_type(当然还有boost::type_traits::common_type)使用三元操作符来检索类型结果。在本例中,相关的引用来自CppReference, 6b)

E2和E3具有算术或枚举类型:应用通常的算术转换将它们转换为公共类型,该类型是结果。

有了这些信息,我们可以在c++标准5p10第88页中找到常用算术转换的规则。

—否则,如果无符号整数类型的操作数的排名大于或等于另一个操作数类型的排名,则将有符号整数类型的操作数转换为无符号整数类型的操作数的类型。

所以基本上你的问题的答案是:…因为标准是这么说的

但你不是唯一一个发现这种行为出乎意料的人。下面是一个可以快速运行的示例:

#include <iostream>
#include <typeinfo>
#include <type_traits>
int main(int argc, const char* argv[])
{
    std::cout << typeid(std::common_type<char, unsigned char>::type).name() << std::endl;
    // I would expect "short", and the result is "int", ok so far.
    std::cout << typeid(std::common_type<short, unsigned short>::type).name() << std::endl;
    // I would expect "int", and the result is "int", yay.
    std::cout << typeid(std::common_type<int, unsigned int>::type).name() << std::endl;
    // I would expect "long", but the result is "unsigned int"
    std::cout << typeid(std::common_type<long, unsigned long>::type).name() << std::endl;
    // I would expect "long long", but the result is "unsigned long"

    // So this usual arithmetic conversion can lead to unexpected behavior:
    auto var_auto = true ? var_i : var_ui;
    std::cout << typeid(var_auto).name() << std::endl;   // unsigned int
    std::cout << var_auto << std::endl;                  // 4294967173
    return 0;
}

但是,当前的行为是一个问题是已知的,并且存在一个建议来消除一些意外。

hannes

相关文章: