c++ - 在多个声明中使用 auto 时,为什么需要为所有变量初始化?

标签 c++ c++11 declaration c++14 auto

我预计只有第一个声明才需要初始化程序。例如

auto x = 2, y;

我希望这会将 x 的类型推导为 int,然后隐式地将“auto”替换为基本类型“int”,这意味着 y 将成为默认的初始化整数。实际上,整个事情都无法编译,因为 y 明确需要和初始化程序。同样,这对我来说很奇怪

auto x = 2, y = 3.3;

也会导致错误。我本来希望 y 在 double 到 int 转换中初始化为 3,但是:

error: inconsistent deduction for 'auto': 'int' and then 'double'

我通读了http://en.cppreference.com/w/cpp/language/auto并且无法明确找到解释。实际上,这个链接似乎在我这边:

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).

这只是“正当理由”吗?

最佳答案

Is it simply "just cause"?

是的。

两个变量都有推导类型,因此两个变量都需要一个初始化器。要求两者具有相同类型的逻辑应用于推导后。

[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++ 的怪异之处,但我想它的存在是为了帮助保持标准措辞的简单。毕竟,如果您的示例按照您所描述的方式工作,那不是会有点令人困惑(我的意思是比 auto 已经更加令人困惑/不清楚)吗?

关于c++ - 在多个声明中使用 auto 时,为什么需要为所有变量初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31672968/

相关文章:

c++ - GCC 中的 std::put_time 实现状态?

c - C语言中这个指向指针的指针语句是什么意思?

javascript - NodeJS 提示如果在 if 语句中设置了某个对象,则该对象是未定义的

c++ - 为什么在选择排序中使用 Xor 运算符交换对象不起作用?

c++ - 复合赋值 E1 op= E2 不等同于 E1 = E1 op E2

c++ - 如何绑定(bind)传递未指定调用包装器的成员函数模板

c++ - 如何将 qml 的 console.log() 重定向到 cpp stdout

c++ - std::array<T, N> 的大小是否保证等于 T[N] 的大小?

qt - 为什么 Qt 的容器类不允许可 move 、不可复制的元素类型?

c - 无效函数(int(*比较)(a,b))