gpt4 book ai didi

c++ - 为什么 common_type::type = long long?

转载 作者:IT老高 更新时间:2023-10-28 21:58:29 27 4
gpt4 key购买 nike

common_type<long, unsigned long>::typeunsigned long因为关于积分提升后的操作数,标准说...

[...] if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type

不要称积分提升系统有问题,但似乎如果有更大的有符号整数类型可以表示有符号和无符号操作数的范围,则应该使用它。

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

最佳答案

首先,std::common_type(当然还有 boost::type_traits::common_type)使用三元运算符来检索类型结果。在这种情况下,相关报价来自 CppReference , 6b)

E2 and E3 have arithmetic or enumeration type: usual arithmetic conversions are applied to bring them to common type, that type is the result.

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

— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

所以基本上你的问题的答案是:...因为标准是这样说的。

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

#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;
}

但是当前的行为是一个问题是known , 和 proposal存在是为了消除一些惊喜。

-汉尼斯

关于c++ - 为什么 common_type<long, unsigned long>::type = long long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15211463/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com