HP aC++/HP C A.06.28 Programmer's Guide Integrity servers (769150-001, March 2014)
namespace N { // An extension of the first part of namespace N
char const* f(int); // Leave the implementation to another
} // translation unit.
int main() {
printf(“Calling: %s.\n”, N::f()); // OK, declared and defined above
printf(“Calling: %s.\n”, N::f(7)); // OK, declared above (defined elsewhere)
printf(“Calling: %s.\n”, f(3.0)); // OK, declared above (defined below)
return 0;
}
namespace { // An extension of the unnamed namespace in this translation unit
char const* f(double) { return “f(double) in main() translation unit”; }
}
An Auxiliary Translation Unit
Following is an auxiliary translation unit that illustrates how namespaces interact across translation
units.
namespace { // An unnamed namespace unrelated to the
// one in the other translation units.
char const* f(double) { return “f(double) in auxiliary translation unit”; }
}
namespace N { // This namespace is the same as the
// one in the main() translation unit.
// We implement f(int) here.
char const* f(int) { return “f(int) defined in auxiliary translation unit”; }
}
using- declarations and using- directives
C++ provides two alternatives to explicitly qualifying names in namespaces. These are the using-
declaration and the using- directive.
using- declaration
A using- declaration introduces a declaration in the current scope as follows:
using N::x; // Where N is a namespace, x is a name in N
After this declaration, all uses of x in this scope are taken to defer to N::x. (The N:: prefix is no
longer required.)
If another declaration of x were introduced in the same scope, for example:
int x;
then a compiler error occurs.
using- directive
The using- directive directs the lookup for names not declared in current scope, for example:
using namespace N; // If not found, lookup names in namespace N
If x is a name in namespace N, but another declaration of x is present in the current scope, for
example:
int x;
a compiler error is not necessarily emitted. Only if that name is used will an ambiguity occur.
NOTE: Using- directives are transitive. If you specify a using- directiveto one namespace
which itself specifies a directive to another namespace, then names used in your scope will also
be looked up in that other namespace.
HP aC++ Keywords 145