在基于范围的for的表达式和声明中具有相同名称的标识符
Identifier with the same name in both expression and declaration of range-based for
在基于范围的for循环中声明与我在循环的表达式语句中使用的名称相同的循环变量是否合法?我希望这个例子能让你明白。
#include <iostream>
#include <vector>
struct bar {
std::vector<int> nums;
};
int main()
{
bar b;
b.nums = {1, 2, 3};
for(int b : b.nums)
std::cout << b << std::endl;
}
从我阅读的c++ 2011 6.5.4,你的代码:
bar b;
for(int b : b.nums)
std::cout << b << std::endl;
应转换为:
bar b;
{
auto && __range = b.nums;
for (auto __begin = __range.begin(), __end = __range.end(); __begin != __end; ++__begin ) {
int b = *__begin;
std::cout << b << std::endl;
}
}
这对我来说意味着clang是正确的
叮当声是正确的。
c++ 11标准第6.5.4/1段定义了基于范围的for
语句如下:
对于形式为
的基于范围的 For语句for ( for-range-declaration : expression ) statement
让range-init等价于用圆括号括起来的表达式
( expression )
和基于范围的 for语句,格式为
for ( for-range-declaration : braced-init-list ) statement
让range-init等价于带括号的init-list。在每种情况下,基于范围的for语句都是等效的
{ auto && __range = range-init; for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } }
从上面可以看到,变量b
,对应于for-range-declaration
,是在嵌套块语句中声明的,而初始化器range-init
(对应于b.nums
)出现在父作用域中,其中b
应该解析为类型为bar
的对象。
无论如何,这个错误现在已经在gcc主干上修复了。:)
相关文章:
- #ifdef和未声明的标识符
- 未声明的标识符编译暗黑破坏神 2 程序"muleview"
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- Google protobuf 时间戳未声明标识符,在 Windows 上具有C++
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 使用说明符 extern 声明的C++中的标识符链接
- 使用未声明的标识符"sqrt"?
- 对类 (C++) 中的私有变量使用未声明的标识符
- 我的代码中有错误,未声明的标识符
- 未定义的标识符/未声明
- 错误:在 C++ 'std'使用未声明的标识符
- 在编译器之前检测未声明的标识符
- 使用未声明的标识符'temp'
- 在没有标识符的情况下如何读取复杂的C++类型声明?
- 使用未声明的标识符"yylex"和"yyin"?
- 使用"class"关键字,后跟未声明的标识符
- 未声明的标识符错误,但变量定义正确 (?)
- C2065 'cout':未声明的标识符
- C++模板模板参数中未声明的标识符
- 一种用于从C++迁移到 Python 的技术,用于减少缺少标识符声明的影响