Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The declaration `using namespace C;` is essential to prove the results shown in the Example in [namespace.udir]/3

As far as I know, the declaration using namespace C; below in namespace D is essential for the compiler to complain about the ambiguity between the qualified-ids B::C::i and A::i in the code below, which is an example in the C++ Standard in [namespace.udir]/3:

namespace A {
  int i;
  namespace B {
    namespace C {
      int i;
    }
    using namespace A::B::C;
    void f1() {
      i = 5;        // OK, C​::​i visible in B and hides A​::​i
    }
  }
  namespace D {
    using namespace B;
    //using namespace C;
    void f2() {
      i = 5;        // ambiguous, B​::​C​::​i or A​::​i?
    }
  }
  void f3() {
    i = 5;          // uses A​::​i
  }
}
void f4() {
  i = 5;            // ill-formed; neither i is visible
}

Surprisingly, all three compilers VS2017, GCC and clang show the same error message when the declaration using namespace C; is commented out of the code. What am I missing?

main.cpp:17:13: error: reference to 'i' is ambiguous
       i = 5;      // ambiguous, B::C::i or A::i?
like image 560
Belloc Avatar asked Jul 05 '18 11:07

Belloc


1 Answers

The ambiguity is on account of the earlier using directives:

namespace B {
// ...
  using namespace A::B::C;
// ...
}
namespace D {
  using namespace B;

Since using directives are transitive for unqualified lookup ([namespace.udir]/4).

like image 184
StoryTeller - Unslander Monica Avatar answered Oct 05 '22 22:10

StoryTeller - Unslander Monica