关于在执行不合格调用时使用名称与使用命名空间的歧义
我知道这会是不明确的,
#include <boost/hana/fwd/equal.hpp>
#include <range/v3/algorithm/equal.hpp>
#include <vector>
int main() {
std::vector<int> v{1,2,3};
using namespace boost::hana;
using namespace ranges;
equal(v, v);
}
因为在 boost::hana
和 ranges
命名空间中都有一个 equal
。
然而,我认为这也含糊不清:
#include <boost/hana/fwd/equal.hpp>
#include <range/v3/algorithm/equal.hpp>
#include <vector>
int main() {
std::vector<int> v{1,2,3};
using namespace boost::hana;
using ranges::equal;
equal(v, v);
}
但根据 GCC 和 Clang ,情况并非如此。
这是为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
摘要2
让我们查看示例中的第二个摘要的工作原理,因为您已经知道为什么第一个摘要会产生模棱两可的错误的原因。
来自使用指令的文档::
这意味着使用指令的
不在声明区域中引入名称(示例中
main
函数无非),而是转到最近的封闭式名称空间(哪个是示例中的全局名称空间
)。现在,当不合格的查找发生对呼叫表达式
均等(v,v);
从遇到呼叫表达式的点上向上,并找到相等的
版本是根据使用声明区域中的声明
引入的(main
),因此搜索停止。因此,使用此版本已被使用。一个人为的例子可能有助于澄清情况:
demo
snippet 1
snippet 1 smippet 1在示例中也可以根据示例中的示例来理解上面引用的陈述。特别是,您在摘要1中遇到模棱两可的错误,因为两个命名空间
范围
和boost :: hana
具有称为quode>等于
的函数同样排名。因此,当不合格的名称查找发生在 call expressionquare(v,v)遇到表达式,并找到名为
均等
的函数,由于两个名称空间,它们在全局名称中可见。此外,由于两者都同样排名,因此我们会得到上述模棱两可的错误。一个人为的例子可能有助于澄清情况:
demo
Snippet 2
Lets look at how the second snippet in your example works since you already know the reason for why the first snippet produces ambiguous error.
From Using directives' documentation:
This means that a
using directive
does not introduce name in the declarative region (which is nothing but themain
function in your example), but instead to the nearest enclosing namespace( which is theglobal namespace
in your example).Now, when unqualified lookup happens for the call expression
equal(v, v);
the search goes upwards from the point where the call expression was encountered and it finds theequal
version that was introduced due to theusing declaration
in the declarative region(which ismain
) and hence the search stops. And so this already found version is used.A contrived example might help clarify the situation:
Demo
Snippet 1
Snippet 1 in your example can also be understood based upon the quoted statement above. In particular, you're getting ambiguous error in snippet 1 because both the namespaces
ranges
andboost::hana
have a function calledequal
that are equally ranked. So when the unqualified name lookup happens for the call expressionequal(v,v)
the search starts and goes upwards from the point where the call expression was encountered and finds functions namedequal
that were made visible in the global namescope due to both of the namespaces. Moreover, since both are equally ranked, we get the mentioned ambiguous error.A contrived example might help clarify the situation:
Demo