How to access Unnamed namespace variable nested inside named namespace?

1.9k Views Asked by At

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?

2

There are 2 best solutions below

3
user0042 On

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.

3
9Breaker On

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

}