I’m a bit confused concerning proper usage of C++ namespaces. It is clear for me how they can help to avoid conflicts (name collision), but it is not clear anymore when it comes to the using keyword. I mean, suppose I have a part of my code that I put into a namespace, and create a class, say
namespace my
{
class vector { ... };
}
Of course, when I use it, I wouldn’t like to type my::vector all the time, so I’d like using namespace my. However, I could eventually need something from the std namespace, and then I want using namespace std at the same time, but this will bring me back to the initial name collision problem.
I know that it is possible to “import” only the functionality that I need, like using std::set, but in this case it seems natural to import both the standard namespace std and my namespace completely as I’d use both of them all the time.
Does this mean that even when I use namespaces I should still think about giving non-common names to my types? Or is using namespace a mistake and I should always type my::vector instead? Thanks.
Well, I should probably clarify that it is more a question of readability than typing. Lots of :: everywhere look really weird to me. I know it’s a question of taste and habits, but nevertheless.
Yes, it would bring you back to the initial name collision problem. This is why you should use
using namespace ...;directives sparingly, and only in source files, never in headers.No, you shouldn’t. Namespaces were invented precisely to avoid this.
You can, if you want to, use the
using namespace ...;orusing ...;directives until you get conflicts. This means that when you do have conflicts, you’ll end up writing “unnatural” code by explicitly quallifying names in some places.In practice, when you’re dealing with short namespace names (i.e.
std), you can just type them explicitly all the time. After a week or so, you won’t even notice you’re typing it anymore.