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

标签 c++ namespaces language-lawyer

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/

相关文章:

c++ - 在现有图形应用程序上绘制 DirectX/OpenGL 图形

c++ - 我怎样才能使我的类更加独立于平台?

c++ - 通过对象指针访问成员

c++ - 即使构造函数具有可观察到的副作用,标准中是否允许消除未使用对象的构造?

c++ - 如何创建可调整大小和固定大小容器的变体

c# - 如何避免在 C# 命名空间中定义冗余枚举?

javascript - 使用命名空间时 jQuery bind() 的行为

c# - XPATHS 和默认命名空间

c++ - 为什么显式声明的构造函数会阻止使用 C++ 11 初始化列表进行成员初始化?

c++ - C++11 是否允许在标识符中使用美元符号?