Is it possible to wrap code in anonymous namespaces to use directives?
I want it to be using namespace std;
applied to classes as well as functions without polluting the global namespace, but I'm wondering if this approach works.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
source to share
It will work, but remember the following points:
-
You should restrict its use in the source file and not in the header file (in general, you should refrain from using unnamed namespaces in the headers as they can easily mess with your character definitions, especially if there are built-in functions that use something from anonymous namespaces).
-
It's bad practice and adding an extra layer of the naming hierarchy (i.e. anonymous namespace) is just for laziness, as bad as it sounds.
source to share
While this looked like a great solution, in my experiments it is not what I expected. This does not limit the scope of the use directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of these lines compile because they are not properly qualified. This is what we expect.
Then consider the following:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
Therefore, placing the using directive in an unnamed namespace looks exactly the same as placing it in the global namespace.
EDIT: Actually, placing a character in an unnamed namespace makes it local to the translation unit. That is why it cannot work as intended.
Therefore, it should be no-no for headers.
source to share