在多个声明中使用 auto 时,为什么需要为所有变量初始化?
How come you need initialisers for all variables when using auto in multiple declarations?
我原以为只有第一次声明才需要初始化程序。例如
auto x = 2, y;
我希望这会将 x 的类型推断为 int,然后将 "auto" 隐式替换为基本类型 "int",这意味着 y 将成为默认的初始化整数。实际上整个事情并没有编译,因为 y 明确需要和初始化程序。同样让我感到奇怪的是
auto x = 2, y = 3.3;
也会导致错误。我希望 y 在 double-to-int 转换中被初始化为 3,但是:
error: inconsistent deduction for 'auto': 'int' and then 'double'
我通读了 http://en.cppreference.com/w/cpp/language/auto,但找不到明确的解释。其实好像link是站在我这边的:
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details).
只是"just cause"吗?
Is it simply "just cause"?
是的。
两个变量都有一个推导类型,因此两个变量都需要一个初始化器。应用要求两者具有相同类型的逻辑post-推导。
[C++11: 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.
[C++14: 7.1.6.4/8]:
If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables. The type of each declared variable is determined as described above, and if the type that replaces the placeholder type is not the same in each deduction, the program is ill-formed.
称它为 C++ 怪癖,但我想它的存在有助于保持标准措辞的简单性。毕竟,如果您的示例如您所描述的那样工作,会不会有点令人困惑(我的意思是 confusing/unclear 已经比 auto
多了)?
我原以为只有第一次声明才需要初始化程序。例如
auto x = 2, y;
我希望这会将 x 的类型推断为 int,然后将 "auto" 隐式替换为基本类型 "int",这意味着 y 将成为默认的初始化整数。实际上整个事情并没有编译,因为 y 明确需要和初始化程序。同样让我感到奇怪的是
auto x = 2, y = 3.3;
也会导致错误。我希望 y 在 double-to-int 转换中被初始化为 3,但是:
error: inconsistent deduction for 'auto': 'int' and then 'double'
我通读了 http://en.cppreference.com/w/cpp/language/auto,但找不到明确的解释。其实好像link是站在我这边的:
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details).
只是"just cause"吗?
Is it simply "just cause"?
是的。
两个变量都有一个推导类型,因此两个变量都需要一个初始化器。应用要求两者具有相同类型的逻辑post-推导。
[C++11: 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 parameterU
is not the same in each deduction, the program is ill-formed.
[C++14: 7.1.6.4/8]:
If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables. The type of each declared variable is determined as described above, and if the type that replaces the placeholder type is not the same in each deduction, the program is ill-formed.
称它为 C++ 怪癖,但我想它的存在有助于保持标准措辞的简单性。毕竟,如果您的示例如您所描述的那样工作,会不会有点令人困惑(我的意思是 confusing/unclear 已经比 auto
多了)?