Context of using declaration and ambiguous declaration

混江龙づ霸主 提交于 2020-01-05 04:25:09

问题


There is a quote from the sec. 3.4.3.2/3:

Given X::m (where X is a user-declared namespace), or given ::m (where X is the global namespace), if S(X, m) is the empty set, the program is ill-formed. Otherwise, if S(X, m) has exactly one member, or if the context of the reference is a using-declaration (7.3.3), S(X, m) is the required set of declarations of m.

Definition of S(X,m) is the following sec. 3.4.3.2/2:

For a namespace X and name m, the namespace-qualified lookup set S(X, m) is defined as follows: Let S (X, m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S (X, m) is not empty, S(X, m) is S (X, m); otherwise, S(X, m) is the union of S(Ni , m) for all namespaces Ni nominated by using-directives in X and its inline namespace set.

Now consider the following code:

#include <iostream>

using namespace std;
namespace N
{
    int cout = 6;
}
using namespace N;

int main() {
    using ::cout;//error: reference to ‘cout’ is ambiguous
    return 0;
}

I don't understand thar error. The code above does not contradict to the rule:

if S(X, m) has exactly one member, or if the context of the reference is a using-declaration (7.3.3), S(X, m) is the required set of declarations of m.

Can you explain the sense of that rule?


回答1:


Dmitry, I suspect you are misinterpreting what "if the context of the reference is a using-declaration" means. "In the context of a using-declaration" does not mean "when used in a using-declaration". It instead means "when the reference is the subject of a using-declaration". Suppose your code is changed as follows:

int main() {
    using N::cout;
    std::cout << "value=" << cout << '\n';
}

Note the use of the unqualified cout in std::cout << "value=" << cout << '\n'. The context of that unqualified reference is the using-declaration using N::cout.

Another way to look at what the standard means is that a using-declaration takes precedence over a using-directive.



来源:https://stackoverflow.com/questions/24268165/context-of-using-declaration-and-ambiguous-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!