gpt4 book ai didi

c++ - qualified::toplevel_namespace 和 unqualified toplevel_namespace 之间有什么区别吗?

转载 作者:行者123 更新时间:2023-11-30 02:44:35 24 4
gpt4 key购买 nike

一般来说,::any_nameany_name的区别should be clear .如果以 :: 开头,则该名称始终且仅在全局命名空间中查找。

不过,我想知道是否存在技术(*) 差异,给定一个我已经知道是toplevelnamespace(即直接位于全局命名空间之下),我知道没有第二个(嵌套的)命名空间(或任何名称) 具有相同的名称。

例如,使用 ::std::stringstd::string 有什么区别吗?


(*) 撇开可读性、风格和维护问题不谈。

最佳答案

"For example, is there any difference between using ::std::string vs. std::string?"

想想这样奇怪的情况

LegacyString.hpp

namespace Legacy {
namespace std {
class string {
// ...
};
}
}

#include <string>
#include "LegacyString.hpp"

using namespace Legacy;

在这种情况下,如果您在以下代码中使用 ::std::string 或仅使用 std::string,肯定会有所不同。

是的,正如您的 other question's accepted answer 中所述, 命名任何构造是完全合法的,无论是 namespaceclassstructtypedef 等。< strong>std.


至于您的问题编辑:

"and where I know that there is no second (nested) namespace (or any name) of the same name."

如果您知道是这种情况,那么这两种形式当然是等价的。正如您提到的,命名空间的解析最终在全局级别进行,并且无需前缀 :: 即可正确解析它。

恕我直言,我们通常依赖于,至少没有人那么愚蠢,可以实际命名任何构造 std。但引用爱因斯坦的话:

"Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe."

关于c++ - qualified::toplevel_namespace 和 unqualified toplevel_namespace 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25169501/

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