c++ - 编译器如何选择给 auto 赋值?

标签 c++ int double auto

首先,我知道这是一个非常简单的问题。我只是在寻找技术解释,说明为什么编译器决定使用 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 to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions shall be performed on both operands.

关于c++ - 编译器如何选择给 auto 赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25464721/

相关文章:

c++ - C++ 标准库如何链接到我的应用程序?

VBA:Variant/Double 和 Double 之间的区别

c++ - 如果两位数精度≈15.955 (16),为什么我可以打印 50 位数字?

c - 双 x 变量的 x=0 和 x=0.0 之间有什么区别? c代码

c++ - 通过引用返回 std::vector 导致段错误

c++ - 函数实际上是如何按值返回的?

c++ - 如何使用libc++用clang编译Google Benchmark

java - 无法从 boolean 值转换为整数

java - 试图比较两个整数

C++ 读取只有数字的文件