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?
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops;
or using 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 in std
and boost
namespace.
Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
template <class T>
void smart_swap(T& a, T& b)
{
using std::swap;
swap(a, b);
}
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 to std::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With