tags:

views:

627

answers:

3

I like the concept of C++ namespaces, because they help to keep the source code concise while avoiding name conflicts. In .cpp files this works very well, using the "using namespace" declaration. However, in header files this cannot be used, as it "breaks open" the namespace, meaning that the "using namespace" not only applies within the current header file, but to everything that is compiled thereafter. This partly nullifies the advantage of namespaces. Consider for example a header file in which the classes "ourlib::networking::IpAddress" and "ourlib::filesystem::Path" are frequently used.

Is there a way to limit the effect of the "using namespace"-declaration in header files?

A: 

You can just import single classes:

using ourlib::networking::lpAddress;

At least if I remember correctly ;)

This might pollute the global namespace still, though. I tend to just live with the long namespace prefixes in header files. This makes it easier to read the header file for other developers (since you don't have to lookup which class comes from which namespace).

OregonGhost
> This might pollute the global namespace< this would pollute to global namespace
Artyom
Depends on what you mean by polluting. In my opinion, importing a single class can by fine if it is limited to implementation files by including a header. I usually only include headers in other headers if it's absolutely necessary, and go with forward declarations instead. That is rather to improve compile times though.
OregonGhost
I forgot to add, other than that, I agree with you. As I said, I use fully qualified names mostly.
OregonGhost
+2  A: 

You may put, most of frequently use classes in ::ourlib namespace like

namespace ourlib {
   using networking::lpAddress;
}

So, if they unique in the project, most likely you would not have problem. So in, any place in headers you would be able access lpAddress directly without putting in into global namespace (I assume all your headers inside namespace ourlib)

Artyom
+2  A: 

No, it can't be done :(

Dimitri C.