在我看来,当有人放入一个恰好与根级命名空间同名的新命名空间并且神秘地改变了许多程序的含义时,使用未锚定的命名空间只会引发麻烦.那么,为什么人们总是说std::而不是::std::.他们真的应该说"我想用任何std方便的东西,而不是根本的东西."?
这是我的意思的一个例子:
在fred/Foo.h中:
#include <string>
namespace fred {
class Foo {
public:
void aPublicMember(const std::string &s);
};
} // end namespace fred
Run Code Online (Sandbox Code Playgroud)
在fred/Bar.h中:
namespace fred {
namespace std { // A standard fred component
class string { // Something rather unlike the ::std::string
// ...
};
} // namespace std
class Bar {
public:
void aPublicMember(std::string &s);
};
} // namespace fred
Run Code Online (Sandbox Code Playgroud)
在oops.cpp中:
#include <string>
#include "fred/Bar.h"
#include "fred/Foo.h" // Oops, the meaning of Foo is now different.
Run Code Online (Sandbox Code Playgroud)
这是人们想要的,还是我错过了什么?
也许你说你应该永远不要命名命名空间std.这一切都很好,但那么其他一些根级命名空间呢?任何人在任何地方定义的任何根级别命名空间是否总是对子命名空间名称禁止?
为了澄清,我不会考虑任何告诉我std特别的答案,因为我只是以它为例.我说的是一个普遍的问题,我用它std作为道具来说明它,尽管我承认它是一个相当惊人的道具.
Mat*_*son 37
那么,为什么人们总是说std ::而不是:: std ::
可能是因为它们从来没有真正出现歧义问题.
沿着同样的路线:我从来没有在地址中包含"地球",我不会这样做.
你必须在某处绘制线,这是一个合理的假设,其他人不会创建自己的std命名空间,或者至少那个不太受欢迎的库.:)
MSa*_*ers 20
非锚定命名空间的实际原因是一级命名空间通常就足够了.如果不是,通常会将第二级用于实现细节.最后,即使使用多个级别,它们仍然通常从根级别隐式指定.即.甚至在命名空间内ns1,你通常会引用ns1::ns2::foo而不是ns2::foo或::ns1::ns2::foo.
因此,由于这三个原因,::ns1在正常情况下表格是多余的.我认为这是Boost提交的唯一情况,因为作为Boost作者,我不知道我的软件将在何处使用.
为什么人们总是说std ::
不总是.我用string和using ::std::string.所以没有什么不好的fred::std::string,因为我仍然会使用std::string.在小的cpp文件中,它可以是均匀的using namespace ::std.样品:
#include <iostream>
using ::std::string;
//using namespace ::std; // good for small cpp-files
int main()
{
string s = "sometext"; // no leading ::std
}
Run Code Online (Sandbox Code Playgroud)
你应该永远不要命名一个命名空间std
是的,您不应该std为自定义命名空间命名.