C++用于 std 和 boost 命名空间的最佳实践
可能的重复:
您更喜欢 C++ 中的显式命名空间还是“using”?
我是一名 C# 开发人员,但我的朋友是一名 C++ 开发人员。他向我展示了充满诸如 std::for_each
和 boost::bind
之类的调用的代码。我在 C# 中使用过,并认为使用指令会提高代码的可读性并且通常会加快开发速度。例如,在 C# foreach 语句之前键入任何命名空间都会很麻烦。
我想知道使用这种流行的命名空间有什么缺点和优点?
包含这些命名空间是否是最佳实践?
Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?
I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each
and boost::bind
. I used in C# and thought that using directives would rock for readability of the code and generally faster development. It would be a pain in the neck to type any namespace before C# foreach statement for example.
What are the cons and pros of using for such popular namespaces I am wondering?
Is it a best practice to include those namespaces or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,让我们区分两个:
1) 有 using 指令,如
using namespace std;
和 using 声明,如using std::cout;
2) 你可以把 using头文件 (.h) 或实现文件 (.cpp) 中的指令和声明
此外,使用指令和声明将名称带入编写它们的名称空间中,即
现在,就最佳实践而言,很明显,将在全局命名空间的头文件中使用指令和声明是一个可怕的禁忌。人们会因此讨厌你,因为任何包含该标头的文件都会污染其全局命名空间。
将 using 指令和声明放在实现文件中在某种程度上更容易接受,尽管它可能会或可能不会使代码变得不太清晰。一般来说,在这种情况下,您应该更喜欢使用声明而不是指令。我自己的偏好是始终指定名称空间,除非它太长(那么我可能会受到诱惑)。
在标头中,如果每次输入名称空间变得非常乏味,您始终可以引入“本地”名称空间,例如
但永远不要将
using namespace boost;
或等效的位置放在会拖拽所有内容的地方将 Boost 中的内容放入全局命名空间本身以供其他人使用。First of all, let's make two distinctions:
1) There are using directives like
using namespace std;
and using declarations likeusing std::cout;
2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)
Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.
Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.
Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).
In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.
But never put
using namespace boost;
or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.我反对
using namespace
语句,除非在函数体内本地。在每个标识符之前编写完全限定的命名空间一点也不痛苦,除非您每天编写 500 个 loc 左右。I am against the
using namespace
statements, except maybe locally in a function's body. It's not a pain at all to write the full-qualified namespace before every identifier, except if you're writing like 500 loc per day.