01zhou
01zhou

Reputation: 334

Using declaration in C++

namespace A {
  void F() {}
  namespace B {
    void F(int) {}  
  }
}

using A::B::F;

namespace A {
  void G() {
    F();   // OK
    F(1);  // Error: too many arguments to function void A::F()
  }
}

int main() { return 0; }

I have this piece of code.

I defined two functions with same names but different signatures.

Then I use a using-declaration using A::B::F.

In A::G() compiler tries to resolve A::F() before A::B::F().

Are there any orders if there are such conflicts?

Upvotes: 2

Views: 108

Answers (2)

davepmiller
davepmiller

Reputation: 2708

It's definitely about placement.

namespace A {
  void G() {


    F();   // OK, A::F

    using B::F;
    F(1);  // OK, A::B::F
  }
}

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119174

The deepest nested scope is searched first, and scopes are then searched outward if the name is not found. So first it would find a block-scope declaration of F inside G, if any; then it would find a declaration at the namespace scope of A, if any; and if that too failed it would search the global scope. Since using A::B::F; appears at global scope, A::F is always found first. Perhaps you should move the using declaration inside A.

Upvotes: 4

Related Questions