"using namespace" statement inside an anonymous namespace - c++

When using a using namespace statement inside an anonymous namespace bring the namespace used in to the file scope? Eg:
namespace foo
{
int f() { return 1; }
}
namespace
{
using namespace foo;
}
int a()
{
return f(); // Will this compile?
}

According to 7.3.4 [namespace.udir] paragraph 4 a namespace directive is transitive:
For unqualified lookup nominates a second namespace that itself contains using-directives, the effect is as if the using-directives from the second namespace also appeared in the first.
... and according to 7.3.1.1 [namespace.unnamed] paragraph 1 there is kind of an implicit using directive for the unnamed namespace:
An unnamed-namespace-definition behaves as if it were replaced by
inline namespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }
where inline appears if and only if it appears in the unnamed-namespace-definition, all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the entire program.
Thus, the answer is "yes, this is supposed to compile" (and it does with all C++ compilers I tried it with).

Yes.
This is because an anonymous namespace is automatically brought into the containing scope.

Yes, because, as Dietmar Kühl quoted, an anonymous namespace is replaced by its content.
However, you should pay attention that it is replaced exactly where it is declared (edit), so there is no "magic" in this. For example, this won't work:
namespace foo
{
int f() { return 1; }
}
int a()
{
return f(); // Will this compile?
}
namespace
{
using namespace foo;
}

Related

C++: using directive statement in main function Vs global scope

Following code results in an error as it is not considering ::x in global scope.
#include<iostream>
namespace nspace
{
int x = 2;
}
int main()
{
using namespace nspace;
std::cout << ::x; //error: ‘::x’ has not been declared
return 0;
}
Following code results in output 2 without any compilation error.
#include<iostream>
namespace nspace
{
int x = 2;
}
using namespace nspace;
int main()
{
std::cout << ::x; // Outputs 2
return 0;
}
I was under the impression that if we have using directive within main function vs using directive in global scope, it is same as far as main function is concerned. For main function both should introduce nspace::x in global scope. And both should result in same behaviour. But above code contradicts my understanding.
So if you can point me to some text from standard that clarifies above behaviour then it would be helpful.
[namespace.qual]/1:
Qualified name lookup in a namespace N additionally searches every element of the inline namespace set of N ([namespace.def]). If nothing is found, the results of the lookup are the results of qualified name lookup in each namespace nominated by a using-directive that precedes the point of the lookup and inhabits N or an element of N's inline namespace set.
In the first case, using namespace nspace; inhabits the block scope inside the main function, so it is not considered.
In the second case, using namespace nspace; inhabits the global namespace scope, so it is considered by lookup in the global scope.

How to access Unnamed namespace variable nested inside named namespace?

This question has alreday discussed in the link
unnamed namespace within named namespace but no perfect answers were provided on how to access the variables of unnamed namespace nested under named namespace in case both variables are same
Consider This Code
namespace apple {
namespace {
int a=10;
int b=10;
}
int a=20;
}
int main()
{
cout<<apple::b; //prints 10
cout<<apple::a; // prints 20
}
Unnamed namespace "variable a" is always hidden. How to access "variable a" of unnamed namespace?
Is it even legal to declare unnamed namespaces inside named namespaces?
unnamed namespace "variable a" is always hidden. How to access "variable a" of unnamed namespace?
It looks like you simply cannot qualify an unnamed namespace outside of the enclosing namespace.
Well, here's how to fix the ambiguity:
namespace apple {
namespace {
int a=10;
}
int getPrivateA() {
return a;
}
int a=20;
}
int main() {
cout<<apple::getPrivateA() << endl;
cout<<apple::a << endl;
}
See the Live Demo.
Though I'm aware that doesn't fully answer your question (besides if it's legal to nest unnamed namespaces inside another namespace).
I'll have to investigate what the c++ standard specification with chapters 3.4 and 7.3 a bit more to give you a definite answer why it's not possible what you want to do.
I read this the other day and have an answer for "How to access "variable a" of unnamed namespace?"
I answer this knowing fully that it isn't a perfect answer, but it is a way to access the "a" from the unnamed namespace.
#include <iostream>
#include <stdio.h>
namespace apple {
namespace {
int a=257;
int b=10;
}
int a=20;
}
using namespace std;
int main() {
int* theForgottenA;
// pointer arithmetic would need to be more modified if the variable before
// apple::b was of a different type, but since both are int then it works here to subtract 1
theForgottenA = &apple::b - 1;
cout << *theForgottenA; //output is 257
}

Is it ok to wrap code in anonymous namespaces for using directives? [duplicate]

This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#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()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.

Anonymous Namespace

A recent thread on SO triggerred this.
An anonymous namespace is considered to be equivalent to
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
I fail to recollect the exact reason as to why it is not equivalent to
namespace unique { namespace-body }
using namespace unique;
Also tried searching (including google) but in vain. Please share any information you have in this regards.
The specification that exists now was introduced in 1995 in N0783 to correct for a corner case. To quote that paper (page 9):
The WP defines the semantics of an unnamed namespace as being equivalent to:
namespace UNIQUE {
// namespace body
}
using namespace UNIQUE;
This is incorrect because it makes the code in an unnamed namespace dependent on
whether the code is in an original namespace or a namespace extension.
namespace {} // If you remove this line, the
// use of ::f below is invalid
namespace {
void f()
{
using ::f;
}
}
The WP should be changed to define an unnamed namespace as being equivalent to:
namespace UNIQUE {}
using namespace UNIQUE;
namespace UNIQUE {
// namespace body
}

C++ Namespace question

I am working on some code written by a co-worker who no longer works with the company, and I have found the following code: (which I have cut down below)
namespace NsA { namespace NsB { namespace NsC {
namespace {
class A { /*etc*/ };
class B { /*etc*/ };
}
namespace {
class C { /*etc*/ };
}
} } }
I don't understand the purpose of the namespace commands on lines 3 and 8.
Can someone explain what the purpose of an namespace entry with no name is?
Thanks
That's an "anonymous namespace" - which creates a hidden namespace name that is guaranteed to be unique per "translation unit" (i.e. per CPP file).
This effectively means that all items inside that namespace are hidden from outside that compilation unit. They can only be used in that same file. See also this article on unnamed namespaces.