Using-declaration to move name to another namespace?
-
29-09-2019 - |
문제
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?
해결책
With a, they are actually different functions, but with b, the two functions are identical:
assert(&One::foo == &Two::foo);
This would rarely matter; a bigger concern is duplicating the logic.
다른 팁
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 the foo()
function inside Two
, but the a) case generates the code for foo
twice, because the compiler doesn't have any hint in discovering it is the same function.