使用声明将名称移动到另一个名称空间?
鉴于:
namespace One {
void foo(int x) {
munch(x + 1);
}
};
namespace Two {
// ... see later
}
...
void somewhere() {
using namespace Two;
foo(42);
...
以下两个变体之间有什么区别:
a)
namespace Two {
void foo(int x) {
munch(x + 1);
}
};
和b)
namespace Two {
using One::foo;
};
编辑:很明显(a)重复了代码,这永远不是一个好主意。问题更多地是关于重载解析等......如果可能在其他命名空间中存在其他 foo 或 munch 该怎么办?
Given:
namespace One {
void foo(int x) {
munch(x + 1);
}
};
namespace Two {
// ... see later
}
...
void somewhere() {
using namespace Two;
foo(42);
...
is there any difference between the following two variants:
a)
namespace Two {
void foo(int x) {
munch(x + 1);
}
};
and b)
namespace Two {
using One::foo;
};
EDIT: It's pretty clear that (a) duplicates the code which should never be a good idea. The question is more about overload resolution etc. ... what if there are other foo
s or munch
es in possibly other namespaces?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 a,它们实际上是不同的函数,但是对于 b,这两个函数是相同的:
这很少有关系;更大的问题是逻辑重复。
With a, they are actually different functions, but with b, the two functions are identical:
This would rarely matter; a bigger concern is duplicating the logic.
至于用法,它们是等效的。至于代码,在 a) 情况下,您将复制函数
foo()
代码。也就是说,两个版本都将在Two
中提供foo()
函数,但 a) 情况会为foo
生成两次代码,因为编译器没有任何提示发现它是相同的函数。As for the usage they are equivalent. As for code, in case a) you're duplicating the function
foo()
code. That is, both versions will make available thefoo()
function insideTwo
, but the a) case generates the code forfoo
twice, because the compiler doesn't have any hint in discovering it is the same function.