当在 C++11 中使用带有两个声明的 auto 时会发生什么?
What happens when one uses auto with two declarations in C++11?
假设有这样一个循环:
for(size_t i=0, n=ar.size(); i<n; ++i)
{
// ...
}
重写为:
会不会好
for(auto i=0, n=ar.size(); i<n; ++i)
{
// ...
}
换句话说,i
和 n
这两个变量最终总是相同的数据类型。
当我尝试这样的事情时:
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
假设有这样一个循环:
for(size_t i=0, n=ar.size(); i<n; ++i)
{
// ...
}
重写为:
会不会好for(auto i=0, n=ar.size(); i<n; ++i)
{
// ...
}
换句话说,i
和 n
这两个变量最终总是相同的数据类型。
当我尝试这样的事情时:
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