gpt4 book ai didi

c++ - 局部变量可以与命名空间同名吗?

转载 作者:可可西里 更新时间:2023-11-01 16:09:57 25 4
gpt4 key购买 nike

GCC、clang 和 VS2013 编译下面的代码片段:

namespace A{}
int main()
{
int A;
}

但是 [namespace.alias]/4 表示如下:

A namespace-name or namespace-alias shall not be declared as the name of any other entity in the same declarative region.

[basic.scope.declarative]/1 说:

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.

也就是说,我的印象是 main() 中的 int 变量不能与命名空间 A 同名。观察 [basic.scope.declarative]/2 中的例子似乎证实了这一点,当它说

The declarative region of the first j includes the entire example.

最佳答案

来自[basic.scope.declarative],“声明区域”的定义是:

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.

限制是,强调我的:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name
— they shall all refer to the same entity, or all refer to functions and function templates

回到你的例子。如果我们注释这两个声明区域,我们有:

namespace A{}    + region #1
|
int main() | +
{ | |
int A; | | region #2
| |
} + +

namespace A (#1) 和 int A (#2) 的声明区域不同(第二个是第一个的严格子集,但不是没关系)。由于它们不同,因此对使用单一名称的限制不适用。 #2 中有一个 A,#1 中有一个 A

但是,如果我们将 int A 移动到相同的声明区域中:

namespace A {}     +   the only declarative region. even though the
int A; | potential scope of "int A" does not include
| "namespace A", the declarative region does.
int main() { | The intent of this is expressed in the example
| in [basic.scope.declarative]/2:
| int main() {
| int i = j, j;
| j = 42;
| }
|
| "The declarative region of the [j] includes all
| the text between { and }, but its potential scope
} + excludes the declaration of i."

这将违反 [basic.scope.declarative]/4,并且 gcc 和 clang 都正确地拒绝代码:

error: redefinition of 'A' as different kind of symbol

请注意,作为 Vaughn Cato指出,有一个active defect report关于声明区域的措辞。

关于c++ - 局部变量可以与命名空间同名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com