仅当它不是模板时才编译具有结构类型的同名变量
为什么只有在不是模板的情况下才允许具有结构类型同名的变量?
为什么这被认为是可以的:
struct Foo {
int func(int) const;
};
struct Foo Foo;
但不是这样:
template<bool x = true>
struct Foo {
int func(int) const;
};
struct Foo<> Foo;
// gcc 11.2
<source>:6:14: error: 'Foo<> Foo' redeclared as different kind of entity
6 | struct Foo<> Foo;
| ^~~
<source>:2:8: note: previous declaration 'template<bool x> struct Foo'
2 | struct Foo {
| ^~~
Compiler returned: 1
// clang 13.0.1
<source>:6:14: error: redefinition of 'Foo' as different kind of symbol
struct Foo<> Foo;
^
<source>:2:8: note: previous definition is here
struct Foo {
^
1 error generated.
Compiler returned: 1
Why is it allowed to have a variable with same name with a struct type only if it's not a template?
Why is this considered okay:
struct Foo {
int func(int) const;
};
struct Foo Foo;
but not this:
template<bool x = true>
struct Foo {
int func(int) const;
};
struct Foo<> Foo;
// gcc 11.2
<source>:6:14: error: 'Foo<> Foo' redeclared as different kind of entity
6 | struct Foo<> Foo;
| ^~~
<source>:2:8: note: previous declaration 'template<bool x> struct Foo'
2 | struct Foo {
| ^~~
Compiler returned: 1
// clang 13.0.1
<source>:6:14: error: redefinition of 'Foo' as different kind of symbol
struct Foo<> Foo;
^
<source>:2:8: note: previous definition is here
struct Foo {
^
1 error generated.
Compiler returned: 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 C++ 标准(C++ 20、13 模板),类模板名称在其声明区域中应是唯一的。
例如,main 中的这个声明
是正确的。
对于这些声明
,变量
Foo
的声明隐藏了声明的结构的名称。在 C 结构中,标记名称和变量名称位于不同的名称空间中。因此,为了保持与 C 的兼容性,C++ 中允许使用此类声明。要在变量声明后引用结构类型,您需要使用结构类型的详细名称。
According to the C++ Standard (C++ 20, 13 Templates) class template name shall be unique in its declarative region.
So for example this declaration in main
will be correct.
As for these declarations
then the declaration of the variable
Foo
hides the name of the declared structure. In C structure tag names and variable names are in different name spaces. So to preserve the compatibility with C such declarations in C++ are allowed.To refer to the structure type after the variable declaration you need to use the elaborated name of the structure type.