简体   繁体   English

算术运算的自动提升

[英]Automatic promotion of arithmetic operations

Please see the following code:请看以下代码:

#include <type_traits>
int main()
{
    using T = short;
    auto x = T(1) + T(1);
    static_assert(std::is_same_v<decltype(x), T>);
}

It seems that the above static_assert fails for all of gcc, clang, and msvc and I can't see why.似乎所有 gcc、clang 和 msvc 的上述static_assert都失败了,我不明白为什么。 The assertion still fails if I change short into any of bool , char , signed char , unsigned char , and unsigned short , because for all of those cases decltype(x) is deduced to be int .如果我将short更改为boolcharsigned charunsigned charunsigned short中的任何一个,断言仍然失败,因为对于所有这些情况, decltype(x)都被推断为int

Is this the correct behavior given what's explained in https://en.cppreference.com/w/cpp/language/operator_arithmetic ?鉴于https://en.cppreference.com/w/cpp/language/operator_arithmetic中的解释,这是正确的行为吗?

Yes, this promotion from short to int is required.是的,这种从shortint的提升是必需的。

From https://en.cppreference.com/w/cpp/language/operator_arithmetic :https://en.cppreference.com/w/cpp/language/operator_arithmetic

If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion.如果传递给算术运算符的操作数是整数或无作用域枚举类型,则在任何其他操作之前(但在左值到右值转换之后,如果适用),操作数会经历整数提升。

And from https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion (emphasis mine):https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion (强调我的):

prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int).小整数类型(如 char)的纯右值可以转换为较大整数类型(如 int)的纯右值。 In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.特别是,算术运算符不接受小于 int 的类型作为 arguments,并且在左值到右值转换后自动应用整数提升(如果适用)。

and finally:最后:

signed char or signed short can be converted to int; signed char 或signed short 可以转换为int;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM