為什么只有在不是模板的情況下才允許使用具有相同名稱的結構型別的變數?
為什么這被認為是可以的:
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
https://godbolt.org/z/s94n115fq
uj5u.com熱心網友回復:
根據 C 標準(C 20、13 模板),類模板名稱在其宣告區域中應是唯一的。
7 類模板不得與同一范圍 (6.4) 中的任何其他模板、類、函式、變數、列舉、列舉器、命名空間或型別具有相同的名稱,但 13.7.6 中規定的除外。除了一個函式模板可以被同名的非模板函式(9.3.4.6)或其他同名的函式模板(13.10.4)多載外,在命名空間范圍或類范圍內宣告的模板名稱應在該范圍內是獨一無二的。
因此,例如 main 中的這個宣告
template<bool x = true>
struct Foo {
int func(int) const;
};
int main()
{
struct Foo<> Foo;
}
將是正確的。
至于這些宣告
struct Foo {
int func(int) const;
};
struct Foo Foo;
然后變數的宣告Foo隱藏了宣告的結構的名稱。在 C 結構中,標記名稱和變數名稱位于不同的名稱空間中。因此,為了保持與 C 的兼容性,允許在 C 中進行此類宣告。
要在變數宣告后參考結構型別,您需要使用結構型別的詳細名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440073.html
