Page 1 of 1
anonymous namespaces
Posted: September 28th, 2004, 3:21 pm
by poochie
If I have the following anonymous namespace definition:namespace { int x1; namespace{ int x2; namespace { int x3; } }}x1 can be referenced as ::x1. What is the correct syntax for referencing x2 and x3 ?
anonymous namespaces
Posted: November 15th, 2004, 8:26 am
by poochie
hmnn... anybody ?
anonymous namespaces
Posted: November 15th, 2004, 9:52 am
by DominicConnor
Rather has the look of a trick question at an interview.For the life of me I can't see how there can be any "correct" syntax for this.Formally :: is known as the scope resolution operator, which to me implies an operand of a scope.However, there is probably something nasty you can do with the exact form of name mangling used by your compiler.
anonymous namespaces
Posted: November 15th, 2004, 1:25 pm
by Athletico
I'm with DCFC - this has the look of a trick question. The compiler silently generates a globally unique namespace id when you declare an anonymous namespace, e.g. namespace { int xi;}is the same as namespace <unique> { int xi;}using namespace <unique>;where <unique> is some random compiler-generated name. Therefore the inner anonymous namespaces serve no functional purpose.I suspect Visual C++ treats your example syntactically as if the nested anon namespaces weren't there, so you'd access x2 and x3 exactly as you do x1.
anonymous namespaces
Posted: November 15th, 2004, 3:31 pm
by poochie
Athletico/DCFC,Many thanks for your answers.This is certainly not a trick question I made up. In fact, I had actually seen something like that in (bad ?) production code, though the nested declarations were redundant and not referenced outside.>>>>>>>I suspect Visual C++ treats your example syntactically as if the nested anon namespaces weren't there, so you'd access x2 and x3 exactly as you do x1. >>>>>>>>>>You seem to be right about that. Didn't occur to me earlier.>>>>>>>>>>Formally :: is known as the scope resolution operator, which to me implies an operand of a scope.>>>>>>>>>>>Yep, so ::x1 resolves from global namespace. No need to get into the name mangling scheme or the unique identifier.The following program ( which runs under Visual C++) should illustrate :#include <iostream>namespace { int x1=1;namespace{ int x2=2;namespace { int x3=3; }}}main(){ std::cout<<::x1; std::cout <<::x2; std::cout <<::x3;}
anonymous namespaces
Posted: November 19th, 2004, 12:04 pm
by Cuchulainn
The following program ( which runs under Visual C++) should illustrate :#include <iostream>namespace { int x1=1;namespace{ int x2=2;namespace { int x3=3; }}}Why in heaven's name would you ever want this? Was the person who did it feeling alright?