c++ - 当在 C++11 中使用带有两个声明的 auto 时会发生什么?

标签 c++ c++11 auto

假设有这样一个循环:

for(size_t i=0, n=ar.size(); i<n; ++i)
{
  // ...
}

重写为:

for(auto i=0, n=ar.size(); i<n; ++i)
{
  // ...
}

换句话说,in 这两个变量总是以相同的数据类型结束。

当我尝试这样的事情时:

auto i=0, s="";

g++ 4.8.4 生成错误 inconsistent deduction for ‘auto’: ‘int’ and then ‘const char*’。但我无法确定它是否只是 g++,或者根据标准实际上需要在类型推导中使用每个值。

最佳答案

这是 [dcl.spec.auto, 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.

也就是说,所有推导的类型必须相同。

同段中甚至还有一个例子:

auto x = 5, *y = &x;       // OK: auto is int
auto a = 5, b = { 1, 2 };  // error: different types for auto

关于c++ - 当在 C++11 中使用带有两个声明的 auto 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778604/

相关文章:

c++ - 以编程方式更改图像源

c++ - 如何在 "first-chance"期间使用 VS 调试器检查 C++ 异常对象?

c++ - C++0x 是否支持匿名内部类?

c++14 - 如何禁用实例化临时类?

c++ - Qt 安装程序框架 : How to sign the maintenancetool. exe

c++ - 使用 std::function 移动语义

c++ - bsoncxx::to_json 返回损坏的字符串

c++ - 为什么带有初始化程序的C++ 17 if语句无法按预期工作?

c++ - 常量自动引用绑定(bind)到(空)指针 - 实际类型是什么?

c++ - Solaris CC 要求的 template<> 语法,但被 MSVC 和 GCC 禁止