C++ – When to import names into the global namespace? (using x::y, from x import y etc.)

cimportlanguage-featuresnamespacepython

I've been programming in various languages for about 10 years now. And I still haven't figured out when it is a good idea to import something into the global namespace (using x::y in C++, from x import y in Python etc.), so I hardly ever do it.

It almost always seems like a bad idea to me, if only because it limits the set of variable names I can use. For example: Where I to use using namespace std; or using std::string;in C++, I couldn't use stringas a variable name anymore, which I occasionally do (e.g. for string utility functions).

But I'm wondering: Are there some situations where importing a name into the global namespace really makes sense? Any rules of thumb?

Best Answer

In C++, it's generally frowned upon- especially using namespace std. That std namespace has so many names, many of which are very generic algorithms, you can get some extremely nasty surprises when using namespace std. Something like using std::cout; isn't so bad. But never, ever, using anything into the global namespace in a header file. That's a firing-squad offence.

Related Topic