Actually, the below code can not be compiled with Clang using this command:
clang++ -std=c++11 test.cc -o test
.
I just want to mimic the same behavior as "swapping idiom" in C++ to use "using-directive" to enable ADL. But where am I wrong with the following code? The expected calling priority should be the: N1::foo
> N2::foo
> ::foo
, right?
namespace N1 {
struct S {};
void foo(S s) {
std::cout << "called N1::foo.";
}
}
namespace N2 {
void foo(N1::S s) {
std::cout << "called N2::foo.";
}
}
void foo(N1::S s) {
std::cout << "called foo.";
}
int main() {
using N2::foo;
foo(N1::S{});
}
Error messages:
test.cc:54:3: error: call to 'foo' is ambiguous
foo(N1::S{});
^~~
test.cc:40:8: note: candidate function
void foo(S s) {
^
test.cc:45:8: note: candidate function
void foo(N1::S s) {
^
1 error generated.
Updated:
I changed N2::foo to a template method which can mimic std::swap to some extend. So, the question here is why ::foo
can not be called by "foo(N1::S{});
" in the main
function? Since the function should be much properer than a template function to be called when they have the same priority.
namespace N1 {
struct S {};
/*
void foo(S s) {
std::cout << "called N1::foo, specific one." << '\n';
}
*/
}
namespace N2 { // as a fallback to unqualified name which has no user-defined overload.
template<typename T>
void foo(T) {
std::cout << "called N2::foo, generic one." << '\n';
}
}
void foo(N1::S s) {
std::cout << "called foo." << '\n';
}
int main() {
using N2::foo;
foo(N1::S{});
foo(10); // use generic version.
}