什么是目的:“using namespace”? [英] What's the purpose of: "using namespace"?
问题描述
有令人信服的论据反对 使用namespace std
,为什么它是否被引入到语言中?不要使用命名空间
破坏命名空间的目的?为什么我想使用命名空间写?是否有任何问题,我不知道,由
使用命名空间
优雅地解决,也许在使用std :: swap
idiom或类似的东西?
There are convincing arguments against using namespace std
, so why was it introduced into the language at all? Doesn't using namespace
defeat the purpose of namespaces? Why would I ever want to write using namespace
? Is there any problem I am not aware of that is solved elegantly by using namespace
, maybe in the lines of the using std::swap
idiom or something like that?
推荐答案
一方面,这是在命名空间中使用运算符重载的方式(例如使用命名空间std :: rel_ops;
或使用命名空间boost :: assign;
)
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops;
or using namespace boost::assign;
)
简洁也是一个强有力的论据。你真的很喜欢键入和阅读 std :: placeholders :: _ 1
而不是 _1
吗?此外,当您以函数式编写代码时,您将使用 std
和 boost
命名空间中的无数对象。
Brevity is also a strong argument. Would you really enjoy typing and reading std::placeholders::_1
instead of _1
? Also, when you write code in functional style, you'll be using a myriad of objects in std
and boost
namespace.
另一个重要用途(虽然通常不会导入整个命名空间)是启用参数相关的查找:
Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
template <class T>
void smart_swap(T& a, T& b)
{
using std::swap;
swap(a, b);
}
如果在与T相同的命名空间中某些类型的T重载交换,这将使用那个重载。如果你明确调用 std :: swap
,那么不会考虑该重载。对于其他类型,这可以回到 std :: swap
。
If swap is overloaded for some type of T in the same namespace as T, this will use that overload. If you explicitly called std::swap
instead, that overload would not be considered. For other types this falls back to std::swap
.
命名空间的用途,因为在歧义的情况下,您可以随时完全限定名称。
BTW, a using declaration/directive does not defeat the purpose of namespaces, since you can always fully qualify the name in case of ambiguity.
这篇关于什么是目的:“using namespace”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!