首先,我知道这是一个非常简单的问题。我只是在寻找技术解释,说明为什么编译器决定使用 auto 类型说明符使以下变量成为 double over int 类型:
int value1 = 5;
double value2 = 2.2;
auto value3 = value1 * value2;
我知道编译器将从初始化值派生出 value3 的 double 类型,但为什么会这样呢?
最佳答案
auto
变量类型是根据模板类型推导定义的。像这样:
template<typename T>
void f(T t);
f(value1 * value2); // will call f<double>()
value1 * value2
给出 double
而不是 int
的原因是因为算术转换规则允许转换 int
转换为 double
(反向也是隐式转换,但不是算术转换)。当您对内置类型使用运算符时,“会应用通常的算术转换”。
这是标准第 5 节(表达式)中的规则:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.This pattern is called the usual arithmetic conversions, which are defined as follows:
- If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
- If either operand is of type
long double
, the other shall be converted tolong double
.- Otherwise, if either operand is
double
, the other shall be converted todouble
.- Otherwise, if either operand is
float
, the other shall be converted tofloat
.- Otherwise, the integral promotions shall be performed on both operands.
关于c++ - 编译器如何选择给 auto 赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25464721/