Do I have to put code from .cpp in a namespace from corresponding .h or it’s enough to just write using declaration?
//file .h
namespace a
{
/*interface*/
class my
{
};
}
//file .cpp
using a::my; // Can I just write in this file this declaration and
// after that start to write implementation, or
// should I write:
namespace a //everything in a namespace now
{
//Implementation goes here
}
Thanks.
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 theanamespace. But if you are only defining members then both things will work.When the compiler finds
void my::foo(), it will try to determine whatmyis, and it will find theusing a::my, resolvemyfrom that and understand that you are defining thea::my::foomethod.On the other hand this approach will fail if you are using free functions:
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 definingstd::ostream& ::operator<<( std::ostream &, a::my const & )in the cpp file, which is a different function. Using Koening lookup, whenever the compiler seescout << objwithobjof typea::my, the compiler will look in the enclosing namespaces ofcoutandmy(std, anda) and will find that there is ana::operator<<declared but never defined innamespace a. It will compile but not link your code.