How to access the unnamed namespace with scope resolution?
Asked Answered
E

1

6

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
Endomorphism answered 20/1, 2023 at 22:42 Comment(2)
Related: Unnamed namespace access rulesHopefully
You can't. Unnamed namespace has nothing that you can refer to in qualified name. Closest thing would be wrapping whole unnamed namespace in a named namespace (e.g. detail) or just naming your global variables more specifically.Foehn
U
2

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.

Undersell answered 20/1, 2023 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.