Originally Posted by
laserlight
I don't think that's wise: the unnamed namespace makes any names declared within it have internal linkage, but typically in header files you intend the names declared to have external linkage. What could be done is to use the using directive in a local scope, typically in the scope of an inline function defined in the header. Another possibility is to have the using directive within a named namespace instead, and one would probably have one's own namespace for one's own header, but that's not as foolproof as an unnamed namespace since a using directive for that namespace would then bring the using directive for the std namespace (or whatever other namespaces were involved in using directives in the custom named namespace) into scope.
I see what you mean. You could still use the construct within header-only includes:
Code:
#ifndef DEMO_HPP_
#include <string>
#include <iostream>
namespace demo {
namespace {
using namespace std;
void fun(const string& arg)
{
cout << arg << endl;
}
} // namespace
} // namespace "demo"
#endif // DEMO_HPP_ not defined
Code:
#include "demo.hpp"
#include <string>
using namespace std;
int main()
{
string arg = "Hello World!";
demo::fun(arg);
}
But of course if the user then decides to import the entire "demo" namespace:
Code:
#include "demo.hpp"
#include <string>
using namespace demo;
int main()
{
string arg = "Hello World!"; // Yikes, no complaint from the compiler here!
fun(arg);
}
Side effect being that the entire std namespace gets imported along with it!
So yeah, maybe not the best approach.