Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use multiple namespace in same C++ source file?

Tags:

c++

namespaces

I want to include more than one namespace in the same .cpp file.

While std is widely used, the namespace z3 will be used in about 10% of a 25 KLOC file.

Will it be a good practice to use both as

    using namespace std;
    using namespace z3;

I am thinking of using only std and then use the Z3 methods by mentioning the namespase whenever required. Like,

    using namespace std;

    z3::context c;
    z3::solver s;

Which of these is better practice?

I do not want to rename them into one namespace.

Thanks and regards, Sukanya

like image 347
Sukanya B Avatar asked Jun 03 '17 19:06

Sukanya B


People also ask

Can I use multiple namespaces?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Is it good practice to use namespace?

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.

How many namespaces can you use?

A namespace is like a container for variable and function names. When you have a very large project, you might find that more than one part of the project may use the same name for something. You can use as many namespaces as you'd like in a single source file.

Can you declare two namespaces with the same name?

namespace definitionMultiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.


1 Answers

It's actually best practice not to import the entire namespace into your program because it pollutes your namespace. This can lead to naming collisions. It's best to import only what you are using.

So instead of:

using namespace z3;

You should do:

using z3::context;
like image 131
Tvo Avatar answered Sep 24 '22 02:09

Tvo