如何通过范围解析访问未命名的名称空间?

Joh*_*hnz 6 c++ global unnamed-namespace

我有这个:

#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;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况::val下将提供val = 400. 但是,如果我删除对全局变量的注释,那么全局命名空间将通过::val. 那么,在这种情况下,如何访问未命名的名称空间呢?

int val = 400;

这是输出

// Global variable
int val = 100; //Not commented.
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)

fra*_*sco 2

一个可能的解决方案是通过引用“隐藏”变量来扩展未命名的命名空间:

#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;
}
Run Code Online (Sandbox Code Playgroud)

使用Godbolt检查代码。

程序的输出是:

500
100
200
400
Run Code Online (Sandbox Code Playgroud)

作为旁注:避免using namespace std在标题中。