最佳实践:使用命名空间或重新打开命名空间? [英] Best practices: using namespace or reopen namespace?
问题描述
namespace foo
{
void bar();
...
}
很长时间以来,我一直在重新打开命名空间当我在cpp文件中定义函数时:
namespace foo
{
void bar()
{
doSomething();
...
}
}
这种方式,它被用在我正在工作的项目。我从来没有真正想过,直到最近,当我偶然发现了一个使用using指令的项目:
using namespace foo;
void bar()
{
doSomething();
...
}
最后还有一个使用全名的选项。我觉得很繁琐,特别是当有很多成员的课程涉及。在我看来,当文件的所有内容都是一个命名空间的一部分时,它没有多大意义。
void foo :: bar()
{
doSomething();
...
}
所以我的问题是, ?特别是关于前两个选项(使用指令vs.重新打开命名空间)。
我认为最简单的方法是重新打开命名空间,我有支持它的参数:
- 第二个选项,
using
指令,不清楚是否在该命名空间中实现了一个方法。你也可以实现一个使用命名空间中的东西的自由函数。 - 第三个选项通常用于实现类成员函数。如果直接查看
cpp
文件,不清楚您是否从命名空间实现函数,除非知道命名空间存在。要记住的第一件事是,你正在实现一个类成员函数。 - 第一个是最清晰的。打开命名空间并在其中定义一个函数。该函数是命名空间的一部分,这是实现。
Assume I've declared a function (or class, doesn't matter) in a header file, which is part of namespace foo:
namespace foo
{
void bar();
…
}
For a long time I've been reopening the namespace when I was defining the function in a cpp file:
namespace foo
{
void bar()
{
doSomething();
…
}
}
That is because I learned it this way and it was used in a project I was working on. I never really though about it until recently, when I stumbled upon a project which used the using directive instead:
using namespace foo;
void bar()
{
doSomething();
…
}
Finally there's an option of using the full name. I find it pretty tedious, especially when classes with a lot of members are involved. In my opinion it doesn't make much sense when all content of the file is a part of one namespace.
void foo::bar()
{
doSomething();
…
}
So my question is which one should be preferred and why? Especially regarding the first two options (using directive vs. reopen namespace).
I think the cleanest way is re-opening the namespace, and I've got the arguments to support it:
- with your second option, with the
using
directive, it isn't clear that you're implementing a method in that namespace. You could as well be implementing a free function that uses something from the namespace. - the third option is usually used for implementing class member functions. If you look directly in the
cpp
file, it isn't clear that you're implementing a function from a namespace unless you know that namespace exists. The first thing that comes to mind is that you're implementing a class member function. - the first one is the clearest. You open the namespace and define a function inside it. The function is part of the namespace, and this is the implementation.
这篇关于最佳实践:使用命名空间或重新打开命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!