Search code examples
c++argument-dependent-lookupname-lookup

How does ADL affect this piece of C++ code?


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.
}

Solution

  • In this case, normal name lookup finds N2::foo, and N1::foo is found by ADL, they're both added to the overload set, then overload resolution is performed and the calling is ambiguous.

    BTW: Without using N2::foo; in main(), ::foo will be found by normal name lookup, and N1::foo is found by ADL too; as the result the calling is still ambiguous.

    Updated:

    So, the question here is why ::foo can not be called by "foo(N1::S{});" in the main function?

    Because with the usage of using N2::foo;, the name N2::foo is introduced in the main function. When calling foo the name N2::foo will be found at the scope of main, then name lookup stops, the further scope (the global namespace) won't be examined, so ::foo won't be found and added to overload set at all. As the result N2::foo is called for both cases.

    name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

    BTW: If you put using N2::foo; in global namespace before main, foo(N1::S{}); would call ::foo. Both N2::foo and ::foo are found by name lookup and ::foo wins in overload resolution.

    LIVE