I find it more appropriate to surround all the code that should be in the namespace in the namespace a { ... } block, since this is semantically what you do: you define the elements in the namespace a . But if you only identify participants, then both things will work.
When the compiler finds void my::foo() , it will try to determine that my , and find using a::my , allow my from this and understand that you are defining a::my::foo method.
On the other hand, this approach will fail if you use 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 the program, but what it actually does declares std::ostream& a::operator<<( std::ostream&, a::my const & ) in the header file - without implementation - and defines std::ostream& ::operator<<( std::ostream &, a::my const & ) in the cpp file, which is another function. Using a Koening search, whenever the compiler sees cout << obj with an obj type a::my , the compiler will look in the enclosing name spaces cout and my ( std and a ) and find that there is a::operator<< declared, but not defined in namespace a . It will compile but not link your code.
David Rodríguez - dribeas
source share