简体   繁体   English

C++,命名空间最佳实践

[英]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 .我的项目分为多个模块,它们都具有相似的结构,而不是编写像EntityHandlerInputHandler这样的类,我想使用命名空间并执行Input::HandlerEntity::Handler Now this all seems good to me, but those namespaces are also nested inside one more namespace which also have a Handler class!现在这一切对我来说似乎都很好,但这些名称空间也嵌套在另一个名称空间中,该名称空间也有一个Handler类!

Some people said that this is bad practice and could be confusing, but as part of my style I never use the using <namespace>;有人说这是不好的做法,可能会造成混淆,但作为我风格的一部分,我从不使用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).在许多教程中,建议在 function 声明中使用完全限定的命名空间,即 void doSome (std::vector& data),而不是使用命名空间 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.更少的歧义 - 更好的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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