为什么一元减号进行积分提升? [英] Why does unary minus perform integral promotion?

查看:27
本文介绍了为什么一元减号进行积分提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const auto min = -std::numeric_limits<T>::max();
T x = min; // conversion from 'const int' to 'short', possible loss of data

T 是一个模板参数,在这种情况下是一个 short.一元减法显然执行了积分提升.

T is a template argument, a short in this case. Unary minus apparently performs integral promotion.

  • 为什么一元减号会执行积分提升?
  • 如果将 auto 更改为 T 不会生成警告,但应该将 int 分配给 short.为什么没有警告(可能是 VS 花哨)?
  • Why does unary minus perform integral promotion?
  • If auto is changed to T no warning is generated, but it should be assigning an int to a short. Why isn't there a warning (it could be VS being fancy)?

推荐答案

简短回答:(现在很长是因为人们想要对英语过于迂腐,而这本质上并不准确).

Short answer: (now long because people want to be excessively pedantic about English which by its very nature is not exact).

它不是明确的(如在一元减去数学).但是作为对 POD 数据的任何操作(包括一元减 operation)的一部分,都会对输入参数进行隐式检查(可以在 and 操作中使用的最小整数类型是 intcode>) 所以在一元减号之前的输入有积分提升(mathematical 部分而不是运算部分).POD 上所有操作的输出与输入参数相同(应用积分提升后).因此这里的输出也是一个 int.

Its not explicitly (as in the unary minus mathematical). But as part of any operation (this includes unary minus operation) on POD data there is an implicit check on input parameters (the smallest integer type that can be used in and operation is int) so there is integral promotion on the input before the unary minus (the mathematical part not the operation part). The output of all operations on POD is the same as the input parameters (after integral promotion is applied). Thus here the output is also an int.

长答案:

在 C(以及 C++)中,发生 POD 操作的最小类型是 int.因此,在应用一元减号之前,该值将转换为 int.然后应用一元减号.因此,表达式的结果是 int.

In C (and thus C++) the smallest type that POD operations happen on is int. So before the unary minus is applied the value is converted to int. Then the unary minus is applied. The result of the expression is thus int.

参见此处:C++ 运算符中的隐式类型转换规则

这篇关于为什么一元减号进行积分提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆