How to access the unnamed namespace with scope resolution?

135 views Asked by At

I have this:

#include <iostream>
using namespace std;

// Variable created inside namespace
namespace first
{
    int val = 500;
}

namespace
{
    int val = 400;
}

// Global variable
//int val = 100;

int main()
{
    // Local variable
    int val = 200;

    // These variables can be accessed from
    // outside the namespace using the scope
    // operator ::
    cout << first::val << '\n'; 
    cout << ::val << '\n'; 
    cout << val << '\n'; 

    return 0;
}

The ::val in this case will provide val = 400. But if I remove the comment to the global variable then the global namespace will be reached by ::val. So, in that case, how can I access the unnamed namespace?

int val = 400;

This is the output with

// Global variable
int val = 100; //Not commented.
500
100
200
1

There are 1 answers

0
francesco On BEST ANSWER

A possible solution is to expand the unnamed namespace with a reference to the "hidden" variable:

#include <iostream>


// Variable created inside namespace
namespace first
{
    int val = 500;
}

namespace
{
    int val = 400;
}

// Global variable
int val = 100;

namespace {
    int& access_to_val=val;
}

int main()
{
    using namespace std;

    // Local variable
    int val = 200;

    // These variables can be accessed from
    // outside the namespace using the scope
    // operator ::
    cout << first::val << '\n'; 
    cout << ::val << '\n'; 
    cout << val << '\n';
    cout << access_to_val << '\n'; 

    return 0;
}

Check the code with Godbolt.

The output of the program is:

500
100
200
400

As a side remark: avoid using namespace std in the header.