I looked trough some of my older code and found that I was using the using namespace
directive. From what I read in a lot of google results, it seems that it is never a good idea to use this. Is there actually a valid use case for this construct or was this just a misguided attempt to make peoples lifes easier, that failed?
-
1Maybe your google results are just misguided, or you misinterpreted them, hard to tell since you "forgot" to give any reference.– Doc BrownJan 20, 2018 at 19:07
2 Answers
Yes, certainly there are valid uses for the using namespace
-directive.
For example, if you want to use user-defined literals, there operators must be in-scope, so:
using namespace std::literals;
Or maybe only
using namespace std::string_literals;
Generally, using namespace
is unconscionable when you don't know the exact contents, now and in the future, of the respective namespace. If you do, you are fine. But the poster-child of using namepace
-abuse, namespace std
, is far too big, amorphous and changing for considering it.
-
1So basically anything out of house should not be using 'using namespace'? But also you can't really know the future of your own code, so wouldn't it be better to just not use it at all? Jan 20, 2018 at 14:49
-
1Personally I find the advice not to use
using namespace
statements to be primarily applicable to header files. For source files I’d use them whenever practical. Admittedly that’s not very frequently.– axlJan 21, 2018 at 0:43
The using namespace
directive is useful when you have namespaces that identify your project.
Say you have a project that uses the developerIdentifier::projectName
namespaces. That project has a class exampleClass
and a set of utility functions under the namespace utils
. The fully qualified names of these are developerIdentifier::projectName::exampleClass
and developerIdentifier::projectName::utils
.
You have the header stub exampleClass.hpp
:
#include "utils.hpp"
namespace developerIdentifier {
namespace projectName {
class exampleClass
{
public:
void function1();
void function2();
};
}
}
The matching implementation file exampleClass.cpp
has using namespace developerIdentifier::projectName;
written at the top:
using namespace developerIdentifier::projectName;
void exampleClass::function1() { return utils::frobnicate(1, 2); };
void exampleClass::function2() {};
Because this using namespace
declaration is in the implementation file it won't pollute the namspace of any classes importing exampleClass.hpp
.
This declaration has two benefits:
- You don't have to write fully qualified function signatures like
void developerIdentifier::projectName::exampleClass::function1()
withinexampleClass.cpp
. - You don't have to fully qualify
developerIdentifier::projectName::utils::frobnicate()
withinfunction1()
.
-
2Well, there's nothing stopping you from using the same pattern in the implementation-file as in the header... Jan 20, 2018 at 21:22