Using fully qualified names in C++

孤者浪人 提交于 2019-12-01 03:16:54

They may have found it easier than answering lots of questions from people who tried the example code and found it didn't work, just because they didn't "use" the namespaces involved.

Practices vary - if you're working on a large project with lots of diverse libraries and name clashes, you may wish to proactively use more namespace qualifiers consistently so that as you add new code you won't have to go and make old code more explicit about what it's trying to use.

Stylistically, some people prefer knowing exactly what's being referred to to potentially having to dig around or follow an IDE "go to declaration" feature (if available), while other people like concision and to see fuller namespace qualification only on the "exceptional" references to namespaces that haven't been included - a more contextual perspective.

It's also normal to avoid having "using namespace xxx;" in a header file, as client code including that header won't be able to turn it off, and the contents of that namespace will be permanently dumped into their default "search space". So, if you're looking at code in a header that's one reason they might be more explicit. Contrasting with that, you can having "using namespace" inside a scope such as a function body - even in a header - and it won't affect other code. It's more normal to use an namespace from within an implementation file that you expect to be the final file in a translation unit, compiling up to a library or object that you'll link into the final executable, or perhaps a translation unit that itself creates the executable.

First typedefs:

typedef std::vector<MyTypeWithLongName>::const_iterator MyTypeIt;
//use MyTypeIt from now on

Second "using"

using std::string;
//use string instead of std::string from now on

Third "using namespace"

using namespace std;
//Use all things from std-namespace without std:: in front (string, vector, sort etc.)

For the best practice: Don't use 'using' and 'using namespace' a lot. When you have to use it (sometimes keeps the code cleaner) never put it in the header but in the .cpp file. I tend to use one of those above if the names get really long or I have to use the types a lot in the same file.

If you are writing your own libraries you will certainly have heavy use of namespaces, In your core application there should be fewer uses. As for doing something like std::string instead of starting with using namespace std; imo the first version is better because It is more descriptive and less prone to errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!