问题
It appears that it is not allowed to declare multiple variables of distinct types using the auto
keyword. I can't figure out the wording in the standard that would prevent it however.
auto i = 1, j = 1.0; //deduction failure (several compilers)
Historically I understand since you have only one decl-specifier-spec. However, the rules in the standard don't seem to preclude, in fact they encourage, that auto
can be a distinct type for each. Consider these paragraphs:
8-3 Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
7.1.6.4-7 If the list of declarators contains more than one declarator, the type of each declared variable is determined as described above. [...]
Even without auto
not all variables needed to have the same type, as certain modifiers like *
could be applied to each declarator individually. To me it appears now that the wording allows each auto
declarator to be a completely distinct type.
Which paragraph would prohibit this?
回答1:
Type deduction is performed for every object in the list, but the final result must be a single type [dcl.spec.auto]/7
(emphasis mine):
If the list of declarators contains more than one declarator, the type of each declared variable is determined as described above. If the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.
回答2:
I found the corrected wording (it is one of those which actually differs between the final a late draft and the official standard).
7.1.6.4-7 If the list of declarators contains more than one declarator, the type of each declared variable is determined as described above. If the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.
Where 'U' is described in the previous paragraph to be an invented type used for the deduction of each parameter. It's an unfortunate change to the draft since it would have been a very nice feature. (I may also be misunderstanding the previous paragraph in the standard though, as it also deals with std::initializer_list)
来源:https://stackoverflow.com/questions/16642294/why-must-auto-declarations-all-be-of-the-same-type