namespace IBM = International_Business_Machine;
A namespace alias can also refer to a nested namespace.
namespace IBM = Companies::International_Business_Machine;
namespace X = long_namespace;
namespace Y = long_namespace;
using namespace_name::member_namenamespace blip { int bi = 16, bj = 15, bk = 23; }
int bj = 0;
void manip() { using blip::bi; // bi in manip() refers to blip::bi ++bi; // sets blip::bi to 17
using blip::bj; // hides global bj
++bj; // sets blip::bj to 16
int bk; // local variable bk declared here
using blip::bk; // Error: redeclaration of bk in manip() }
int wrongInit = bk; // Error: bk is not visible in global scope
int main() { manip(); return 0; } ```
using namespace_name #include <iostream>
namespace A {
namespace C {
namespace F {
void foo(int) {
std::cout << "Calls foo(int)\n";
}
}
}
namespace B {
namespace E {
void foo(short) {
std::cout << "Calls foo(short)\n";
}
}
namespace D {
using namespace A::B::E;
using namespace A::C::F;
void test (){
unsigned short ui = 1;
foo(ui);
}
}
}
}
int main() {
A::B::D::test(); // Calls foo(short)
return 0;
}
manip() applies only within the block of the function manip().bj appears to manip() as if it were declared outside the namespace blip, in global scope, at the location where the namespace definition is located. However, there is already a variable named bj in global scope. The use of the name bj within the function manip() is therefore ambiguous: the name refers both to the global variable and to the member of namespace blip. The using directive is not an error, however. Only when bj is used within manip() is the ambiguity error detected. If bj was never used within manip(), no error would be issued.manip() as if they were declared in global scope. This means that local declarations within manip() may hide some of the namespace member names. The local variable bk hides the namespace member blip::bk. Referring to bk within manip() is not ambiguous; it refers to the local variable bk.
namespace blip {
int bi = 16, bj = 15, bk = 23;
}
int bj = 0;
void manip() {
using namespace blip; // using directive
++bi; // OK: sets blip::bi to 17
++bj; // ERROR if used: ambiguous - could refer to global or blip::bj
++::bj; // Explicit: sets global bj to 2
++blip::bj; // OK: sets blip::bj to 16
int bk = 97; // Local variable bk declared, hides blip::bk
++bk; // OK: sets local bk to 98
}
int main(){
manip();
}