【问题标题】:Automatic promotion of arithmetic operations算术运算的自动提升
【发布时间】:2020-08-11 23:40:58
【问题描述】:

请看以下代码:

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

上面的static_assert 似乎对于所有 gcc、clang 和 msvc 都失败了,我不明白为什么。如果我将short 更改为boolcharsigned charunsigned charunsigned short 中的任何一个,断言仍然失败,因为对于所有这些情况,decltype(x) 被推断为int .

考虑到https://en.cppreference.com/w/cpp/language/operator_arithmetic 中的解释,这是正确的行为吗?

【问题讨论】:

  • 积分提升页面说明short提升为int
  • 这可能是一个更好的链接:Integral promotions。两个操作数都至少提升为int(或更大的类型或浮点类型)。

标签: c++ integer-promotion


【解决方案1】:

是的,需要从short 升级到int

来自https://en.cppreference.com/w/cpp/language/operator_arithmetic

如果传递给算术运算符的操作数是整数或无范围枚举类型,则在任何其他操作之前(但在左值到右值转换后,如果适用),操作数会经历整数提升。

来自https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion(强调我的):

小整数类型(如 char)的纯右值可以转换为较大整数类型(如 int)的纯右值。特别是,算术运算符不接受小于 int 的类型作为参数,并且在左值到右值转换后自动应用整数提升(如果适用)。

最后:

signed char 或signed short 可以转换为int;

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 2011-04-23
    • 2012-03-11
    • 2016-04-01
    • 2011-01-26
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多