简体   繁体   中英

C++, namespace best practice

My project is divided into modules and they all share a similar structure, instead of writing classes like EntityHandler and InputHandler , I'd like to use namespaces and do Input::Handler and Entity::Handler . Now this all seems good to me, but those namespaces are also nested inside one more namespace which also have a Handler class!

Some people said that this is bad practice and could be confusing, but as part of my style I never use the using <namespace>; keyword so it will always look explicit. Do you think this would be good practice, and if not can you tell me where this could come back to bite me down the line?

I'm sorry if this has been asked before, the places I looked didn't give good explanations as to why or why not to do this!

I think it is better to fully qualify namespace without using because it allow to get rid of some mistakes when reading and/or compiling code. In many tutorials it is recommended to use fully qualify namespace ie void doSome (std::vector& data) in function declaration instead of placing using namespace std + doSome (vector& data). It is good practice to fully qualify namespace because it allow to reduce type resolve ambiguity errors on a compilation stage. Consider following example:

class A {
private:
    Super::Handler* _handlerOne;
    Super::Entity::Handler* _handlerTwo;
};

It would be hard to do the same when you will be use using:

using namespace Super;
using namespace Super::Handler;

class A {
private:
    Handler* _handlerOne;  // What type compiler place here ??? , we don't know ...
    Handler* _handlerTwo;  // What type compiler place here ??? , we don't know ...
};

Less ambiguities - better code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM