Is there a construction similar to using namespace
that doesn't make the imported symbols visible outside the body (or bodies) of the namespace?
In this example here, every symbol in whatever
and other_namespace
will be accessible through Foo::<name_of_symbol>
as well ... and I'd like a way to prevent that from happening.
namespace Foo {
using namespace whatever;
using namespace other_namespace;
// some definitions
}
As a complete example, this program is valid. If an alternative to using namespace
with the intended semantics existed and were used, it would not be.
namespace a {
int func(int x) {
return 10;
}
}
namespace b {
using namespace a;
}
namespace c {
int do_thing(int x) {
return b::func(57);
}
}
Use :: for classes and namespaces A scope resolution operator without a scope qualifier refers to the global namespace. You can use the scope resolution operator to identify a member of a namespace , or to identify a namespace that nominates the member's namespace in a using directive.
All code in the same file can see the identifiers in an unnamed namespace but the identifiers, along with the namespace itself, are not visible outside that file—or more precisely outside the translation unit.
Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.
You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.
You can use an alias inside an unnamed namespace.
namespace a_long_namespace_name {
void someFunc() {};
}
namespace b {
namespace { // an unnamed namespace
namespace a = a_long_namespace_name; // create a short alias
}
void someOtherFunc() {
a::someFunc();
}
}
b::a::someFunc(); // compiler error
You would still need to be writing the namespace to call a function, but it makes calls way shorter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With