There are convincing arguments against using namespace std
, so why was it introduced into the language at all? Doesn't using namespace
defeat the purpose of namespaces? Why would I ever want to write using namespace
? Is there any problem I am not aware of that is solved elegantly by using namespace
, maybe in the lines of the using std::swap
idiom or something like that?
C++ – Purpose and Usage of ‘using namespace’
c++language-designnamespacesusing-directives
Best Answer
For one thing, this is the way to use operator overloads in a namespace (e.g
using namespace std::rel_ops;
orusing namespace boost::assign;
)Brevity is also a strong argument. Would you really enjoy typing and reading
std::placeholders::_1
instead of_1
? Also, when you write code in functional style, you'll be using a myriad of objects instd
andboost
namespace.Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
If swap is overloaded for some type of T in the same namespace as T, this will use that overload. If you explicitly called
std::swap
instead, that overload would not be considered. For other types this falls back tostd::swap
.BTW, a using declaration/directive does not defeat the purpose of namespaces, since you can always fully qualify the name in case of ambiguity.