Updated answer based on updated question
It is okay to
using namespace std in
It is okay to
using namespace std inside function bodies.
Reason: In both cases, they aren't contagious. Contagiousness is the only reason why they shouldn't be used at the global namespace level in header files.
Single-file C++ projects (having just one
*.cpp file, no headers, e.g. in programming puzzles and competitive programming) can use them liberally.
The only hard rule with
using namespace std; in C++ is this:
- Do not put this in a header file, if this header file needs to be included by multiple source files
- Reason: it is contagious.
Other than that, I suggest taking a pragmatic approach to it:
- Allow importing namespaces as long as it does not cause a compiler warning / ambiguity / conflict.
This brings up the question of: what is the true benefit of having namespaces? The simple answer is disambiguation. But disambiguation for who's benefit?
Disambiguation for programmers?
- This is a relatively minor benefit, because most programmers are already accustomed to object-oriented programming, and the naming of objects is already sufficient for telling about the category and the purpose of that object.
- However, only human can make sense from the name of objects - computers can't. (See the next point about automated tools.)
- The human mind is excellent at resolving ambiguity by taking context and domain knowledge into account.
Disambiguation for automated tools, such as compilers, automatic comment-to-documentation generators (Javadoc, Doxygen, etc), and automatic refactoring tools?
- I would argue that this is a more important reason for using namespaces.
- By putting objects into namespaces, automated tools can present groups of objects as interrelated.
- This helps hierarchical organization of class documentations, enforcement of package visibility rules, and many other neat things.
Therefore, as long as it does not cause a conflict, feel free to import namespaces.