c++ - 如何消除具有相同名称的命名空间和类的歧义

标签 c++ c++11

考虑以下代码:

struct foo {
    typedef int bar;
};

namespace foo {
    class baz {
        /* code */
    };
}

这分布在我必须处理的代码库中,它有时会起作用,但我不明白它是如何工作的。

只要命名空间和类不出现在同一个源中(预处理后),它就会起作用(我理解那部分)。但是,如果命名空间和类突然被预处理器拖入同一个编译单元,它(可能)会发生冲突(我不知道源代码中是否发生过这种情况)。

是否存在允许编译器始终正确解析代码结构的约定?最合乎逻辑的是命名空间和类禁止具有相同的符号。应用的编码风格允许命名空间与类发生冲突,尽管存在歧义,因此我更喜欢一种告诉编译器使用情况的方法,而不是更改编码约定。

类似于:

use_namespace(foo)::baz b; 
use_class(foo) b;

最佳答案

C++11 标准的第 7.3.1/2 段只是禁止:

The identifier in an original-namespace-definition shall not have been previously defined in the declarative region in which the original-namespace-definition appears. The identifier in an original-namespace-definition is the name of the namespace. Subsequently in that declarative region, it is treated as an original-namespacename.

关于您的声明:

As long as the namespace and the class don't occur in the same source (after preprocessing) it will work

这是不正确的。第 7.3.2/4 段(尤其是最后一句)告诉您为什么它似乎“有效”,尽管您的程序格式不正确:

A namespace-name or namespace-alias shall not be declared as the name of any other entity in the same declarative region. A namespace-name defined at global scope shall not be declared as the name of any other entity in any global scope of the program. No diagnostic is required for a violation of this rule by declarations in different translation units.

这意味着您正在使用的代码库具有未定义的行为,这可能是一颗定时炸弹,可能会以难以理解的方式爆炸。

关于c++ - 如何消除具有相同名称的命名空间和类的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16772759/

相关文章:

c++ - 二进制 * 运算符未找到

c++ - 在 Windows 上为 Mac/Linux 编译

c# - 使用字符串的 delim 标记字符串

C++ 11 : Calling a C++ function periodically

c++ - 可以链接具有不同名称的函数

c++ - 与 void(MainWindow::*handler)() 等效的 std::mem_fn 类型是什么?

c++ - 在不使用 getline 的情况下在 C++ 中读取 stdin

c++ - 调整大小时数组 "breaks"

c++ - 是否可以在不使用尾随返回类型语法的情况下通过 lambda 引用返回类型为 T 的对象?

c++ - is_container 特性在 std::set SFINAE 问题上失败