Some code I've been asked to modify looks rather like this:
namespace XXX {
namespace {
// some stuff
} // end of unnamed
// Some stuff within the scope of XXX
} // end of XXX
I'm struggling to see the advantage, if any, of embedding the unnamed namespace within another namespace and I'm considering changing it to:
namespace {
// some stuff
} // end of unnamed
namespace XXX {
// Some stuff within the scope of XXX
} // end of XXX
Any views would be gratefully appreciated.
Okay, turns out that X::<anonymous>::foo()
is visible as X::foo()
. I'm surprised.
So, no, there's very little practical benefit. There may be semantic or documentation implications though.
Well that rather depends on the "stuff", doesn't it?
The existing code allows code in X
to have "private" other stuff that's also in X
but cannot be accessed from outside of X
:
#include <iostream>
namespace X {
namespace {
void foo() { std::cout << "lol\n"; }
}
void bar() { foo(); }
}
int main()
{
X::bar();
// X::foo(); // can't do this directly [edit: turns out we can!]
}
lol\n
Your proposed approach makes that "private stuff" available to the entire translation unit:
#include <iostream>
namespace {
void foo() { std::cout << "lol\n"; }
}
namespace X {
void bar() { foo(); }
}
int main()
{
X::bar();
foo(); // works
}
lol\nlol\n