开发者

Should it be in a namespace?

开发者 https://www.devze.com 2022-12-27 00:41 出处:网络
Do I have to put code from .cpp in a namespace from corresponding .h or it\'s enough to just write using declaration?

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 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.


If I understood the question correctly, you can have just using a::my and then just implement the methods, like

using a::my;

void my::doSomething() {}


You can do it. But, should you?

It's an uncommon practice, and it will probably lead to a proliferation of using a::Type; for every type from namespace 'a' used in the .cc file. Whether that is a good thing is for you to decide, but I'd vote against it :)

0

精彩评论

暂无评论...
验证码 换一张
取 消