The using declaration
You can inject names one at a time into
the current scope with a using
declaration.
Unlike the using directive, which treats names as if they were declared
globally to the scope, a using declaration is a declaration within the
current scope. This means it can override names from a using
directive:
//: C10:UsingDeclaration.h
#ifndef USINGDECLARATION_H
#define USINGDECLARATION_H
namespace U {
inline void f() {}
inline void g() {}
}
namespace V {
inline void f() {}
inline void g() {}
}
#endif // USINGDECLARATION_H ///:~
//: C10:UsingDeclaration1.cpp
#include "UsingDeclaration.h"
void h() {
using namespace U; // Using directive
using V::f; // Using declaration
f(); // Calls V::f();
U::f(); // Must fully qualify to call
}
int main() {} ///:~
The using declaration just gives
the fully specified name of the identifier, but no type information. This means
that if the namespace contains a set of
overloaded functions with the
same name, the using declaration declares all the functions in the
overloaded set.
You can put a using declaration
anywhere a normal declaration can occur. A using declaration works like a
normal declaration in all ways but one: because you don’t give an argument
list, it’s possible for a using declaration to cause the overload
of a function with the same argument types (which
isn’t allowed with normal overloading). This ambiguity, however,
doesn’t show up until the point of use, rather than the point of
declaration.
A using declaration can also
appear within a namespace, and it has the same effect as anywhere else –
that name is declared within the space:
//: C10:UsingDeclaration2.cpp
#include "UsingDeclaration.h"
namespace Q {
using U::f;
using V::g;
// ...
}
void m() {
using namespace Q;
f(); // Calls U::f();
g(); // Calls V::g();
}
int main() {} ///:~
A using declaration is an alias,
and it allows you to declare the same function in separate namespaces. If you
end up re-declaring the same function by importing different namespaces,
it’s OK – there won’t be any ambiguities or
duplications.