Good question, Ryan. What
using namespace
does, imports all the characters from a particular namespace (scope) into the area in which it was used. For example, you can do the following:
namespace A { struct foo {}; } namespace B { using namespace A; struct bar : foo {}; }
In the above examples, all characters in the namespace A
become visible in the namespace B
, as if they were declared there.
This import only affects this translation unit. So, for example, when in your implementation file (i.e. .cpp
) you execute using namespace std;
, you basically import all the characters from the std
into the global scope.
You can also import certain characters, but not all, for example:
using std::cout; using std::endl;
You can do this in the global scope of the namespace or in the scope of functions, for example:
int main () { using namespace std; }
The programmer must decide when to use fully qualified names and when to use the using keyword. It is usually very bad to insert using
in header files. Professional C ++ programmers almost never do this unless it is required to solve a problem, or they are 100% sure that this will not spoil the type resolution for those who use this header.
However, in the source file (none of them contain source files), it's ok to do any use statements if there are no conflicting names in different namespaces. This is just a matter of taste. For example, if there are a lot of characters in different code from different namespaces, I would prefer at least some hints as to where they are declared. But everyone is familiar with STL, so using namespace std;
should never hurt.
There may also be several long namespaces, and in these cases it is convenient to use namespace aliases. For example, there is a Boost.Filesystem library that puts all of its characters in the boost::filesystem
namespace. Using this namespace will be too big, so people usually do something like this:
namespace fs = boost::filesystem; fs::foo (); fs::bar ();
Also, it is almost normal to use namespace aliases in headers, for example:
namespace MyLib { namespace fs = boost::filesystem; }
.. and benefit from less typing. It happens that users who use this header will not import the entire file system library by saying using namespace MyLib;
. But then they will import the "fs" namespace from your library, which may conflict with something else. So it's best not to do this, but if you want it too badly, it's better to say using namespace boost::filesystem
there.
So, back to your question. If you are writing a library using C ++ I / O streams, it is better not to have any using
statements in the headers, and I would go with using namespace std;
in every cpp
file. For instance:
somefile.hpp:
namespace mylib { class myfile : public std::fstream { public: myfile (const char *path);
somefile.cpp:
#include "somefile.hpp" using namespace std; using namespace mylib; myfile::myfile (const char *path) : fstream (path) {