0
namespace A
{
int a = 1;
int x = 2;
}

namespace B
{
int b = 3;
int x = 4;
}

using namespace A;
using namespace B;
using B::x;

int main()
{   
    return x; // error : reference to 'x' is ambiguous
}

How to hide A::x and expose B::x only in such a case?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

2 Answers2

2

You can't.

You brought both names into scope, and that's that.

To fix that, don't do that; avoid using namespace.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Provided that `A` and `B` both have many many different identifiers, except that a few ones are identical. Must I `using A::a1`, ``using A::a2`, ..., `using A::an`, `using B::b1`, ``using B::b2`, ..., `using B::bn`? How tedious it would be! – xmllmx Mar 16 '17 at 11:45
  • 1
    @xmllmx: You can do `using namespace A` in a narrower scope for convenience. Frankly it sounds like your namespaces are poorly laid out. – Lightness Races in Orbit Mar 16 '17 at 11:50
1

using namespace brings that namespace into the current one.

Once you've done that you need to deal with any ambiguities yourself. Normally you use the scope resolution operator for that.

C++ doesn't give you the ability to un-bring in a namespace.

The best bet, by a country mile, is to avoid using namespace in the first place. Learn to love code containing lots of :: operators.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483