Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?
Hi guys Im a C# developer, but my friend is a C++ one and he has shown me the code which is filled with calls like std::for_each and boost::bind , im used to using in C# and thought that using directives would rock for readability of code and generally faster development , it would be a pain in the neck to type any namespace before C# foreach statement for example.
What are the cons and pros of using for such popular namespaces I am wondering? Is it a best practice to include those namespaces or not?
I am against the
using namespace
statements, except maybe locally in a function's body. It's not a pain at all to write the full-qualified namespace before every identifier, except if you're writing like 500 loc per day.First of all, let's make two distinctions:
1) There are using directives like
using namespace std;
and using declarations likeusing std::cout;
2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)
Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.
Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.
Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).
In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.
But never put
using namespace boost;
or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.