What are the rules that control priority during C ++ 11 type inference?

What are the rules that determine the priority in the output of type C ++ 11 for types float / double, for example, when outputting from an expression containing several types, for example:

auto var = float(1) * double(1); 
+2
c ++ c ++ 11 type-inference
source share
3 answers

The result will be double . This is called floating point promotion .

From ISO 14882: 2011 , 4.6 Floating point promotion:

1 A value of type float can be converted to a prvalue of type double. The value does not change.
2 This conversion is called floating point promotion.


As @sftrabbit noted, in 5. Expressions, clause 9 in the new standard:

Many binary operators that expect operands of arithmetic or an enumeration type cause conversions and give similar results. The goal is to give a generic type, which is also a result type.

This pattern is called regular arithmetic conversion, which is defined as follows:

- If one of the operands has an enumeration type with area (7.2), conversions are not performed; if the other operand does not have the same type, the expression is poorly formed.
- If one of the operands is of type long double, the other must be converted to a long double.
- Otherwise, if one of the operands is double, the other must be converted to double.
- Otherwise, if any operand is float, the other must be converted to float.
- Otherwise, integral promotions (4.5) must be performed on both operands.

+8
source share

Type inference does not add anything new, the expression to the right of '=' is evaluated as always, and then its type is used for "auto".

This is a little more interesting when you look at the differences between "auto var" and "auto and var" and the like, but that is not your question.

+2
source share

The answer depends on the types in question. In your specific example, the standard ensures that sizeof(double) >= sizeof(float) so the resulting double * float will always be double . (this is a rule inherited from the C language, and, as a rule, the same thing in many other languages ​​that come from C)

When initializing a variable with the auto keyword, the type of initialization expression is determined - regardless of whether it is returned from the return function, calculation, type decltype, etc. A type depends on implicit and explicit conversions for the types you use.

+2
source share

All Articles