I consider more appropriate to surround all the code that is meant to be in the namespace within a namespace a { ... }
block, as that is semantically what you are doing: you are defining elements within the a
namespace. But if you are only defining members then both things will work.
When the compiler finds void my::foo()
, it will try to determine what my
is, and it will find the using a::my
, resolve my
from that and understand that you are defining the a::my::foo
method.
On the other hand this approach will fail if you are using free functions:
// header
namespace a {
class my { // ...
};
std::ostream & operator<<( std::ostream& o, my const & m );
}
// cpp
using a::my;
using std;
ostream & operator<<( ostream & o, my const & m ) {
//....
}
The compiler will happily translate the above code into a program, but what it is actually doing is declaring std::ostream& a::operator<<( std::ostream&, a::my const & )
in the header file --without implementation--, and defining std::ostream& ::operator<<( std::ostream &, a::my const & )
in the cpp file, which is a different function. Using Koening lookup, whenever the compiler sees cout << obj
with obj
of type a::my
, the compiler will look in the enclosing namespaces of cout
and my
(std
, and a
) and will find that there is an a::operator<<
declared but never defined in namespace a
. It will compile but not link your code.