有关浮点/双精度类型的C ++ 11类型推断中的优先级的规则是什么,例如,从包含多个类型的表达式推断时,如下所示:
auto var = float(1) * double(1);
The result will be a double
. This is called floating point promotion
.
From the standard, ISO 14882:2011 , 4.6 Floating point promotion :
1 A prvalue of type float can be converted to a prvalue of type double. The value is unchanged.
2 This conversion is called floating point promotion.
As noted by @sftrabbit, in 5. Expressions , paragraph 9 in the new standard:
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 (7.2), 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 (4.5) shall be performed on both operands.
The type inference doesn't add anything new, the expression to the right of the '=' is evaluated as always, and the type of it is then used for the 'auto'.
It's slightly more interesting when you look at differences between 'auto var' and 'auto & var' and similar, but that wasn't your question.
The answer depends on the types in question. In your specific example, the standard guarantees that sizeof(double) >= sizeof(float)
therefore the resulting type of double * float
will always be double
. (this is a rule inherited from the C language, and is generally the same in many other languages which derive from C)
When initialising a variable with the auto
keyword, the resulting type of the expression of the initialisation is determined - whether its from a function return, a calculation, a decltype, etc. The type depends on implicit and explicit conversions available for the types which you're using.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.