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?

+3


source to share


4 answers


Don't decide to use an anonymous namespace to limit the scope of a directive using

.



If it is stated that an anonymous (or any other) namespace already exists and you want to take advantage of the benefits using

within it, that's fine if your coding standards are in order.

0


source


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.

+1


source


If it is in a header file, then this is not preferable, as this file may be included in multiple source files. If in some source file its acceptable

0


source


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.

0


source







All Articles