在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?

In implementation files, should we prefer "using namespace" directives or wrapping the implementation in namespace { }?

本文关键字:实现 包装 命名空间 using 我们 文件 namespace 更喜欢 指令      更新时间:2023-10-16

我经常在 cpp 文件中看到写

namespace foo
{
... // implementation of class methods etc, belonging to the namespace foo
} // namespace foo

其中实现由命名空间包装,以便不需要命名空间前缀,例如 foo::some_class::method((。

我也经常看到

using namespace foo;
... // implementation of class methods etc, belonging to the namespace foo

前者似乎暗示您将代码放在该命名空间中,而这并不是真正发生的事情。后者对我来说似乎更干净,更直接。这是纯粹的风格还是有理由不使用第二种形式?

更喜欢扭曲。对于类成员函数,几乎没有区别,因为当您编写:

void clazz::foo() {
// ...
}

然后clazz将由常规的非限定查找查找,这将找到您使用 using 指令引入的类名。

但是,对于免费功能,差异是巨大的,这里

void foo() {
// ...
}

将引入一个新函数,在全局命名空间中声明和定义。它将与命名空间中声明的函数无关。

获得一致性的唯一方法(无需通过命名空间完全限定定义(是将定义包装在重新打开的命名空间中。