Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you prefer explicit namespaces or 'using' in C++?

When using C++ namespaces, do you prefer to explicitly name them, like this:

std::cout << "Hello, world!\n";

Or do you prefer using namespace:

using namespace std;
cout << "Hello, world!\n";

And if if you prefer the latter, do you declare your usings at file or function scope?

Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.

like image 777
Rob Avatar asked Oct 18 '08 11:10

Rob


People also ask

What is the biggest advantage of using namespaces?

The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.

Is using namespace std good or bad?

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.

Do you need using namespace std in C?

using namespace std; are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.

Why should you use namespaces in your programs?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.


2 Answers

I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better.

like image 118
Nazgob Avatar answered Oct 21 '22 16:10

Nazgob


Extra typing is not the issue here. The problem with explicitly qualified names is the visual clutter. Let's face it, C++ syntax is untidy. No need to make this worse by needlessly making names longer and sprinkling the code generously with ::s.

I'm with Jeff Atwood: The Best Code is No Code At All. This is so true.

Namespace imports are a great way of reducing clutter with no drawback: As long as the scope of opened namespaces is reduced to a single compilation unit1, name conflicts, should they appear, can be resolved easily.

Why explicit names should (in general) be more readable has always been a mystery to me. The readers should generally know the code good enough to be able to deduce semantics. If they aren't, the code needs fixing anyway.


1) Corollary: no using in headers!

like image 40
Konrad Rudolph Avatar answered Oct 21 '22 15:10

Konrad Rudolph