Here is a similar question , 但在这个问题上它有效,但是在以下情况下它失败了,为什么?
namespace A
{
int k;
}
namespace B
{
class test{};
void k(const test&){/*do something*/}
}
int main()
{
using namespace A;
k(B::test());//compile error
}
错误信息是:“‘A::k’不能用作函数”(gcc 6.3.0)
也就是说,编译器不会尝试执行ADL,也永远不会在namespace B
中找到void k(const test&)
不过,我认为ADL应该在这种情况下工作,因为上面的代码不属于以下情况:
引自cppref
First, the argument-dependent lookup is not considered if the lookup set produced by usual unqualified lookup contains any of the following:
1) a declaration of a class member
2) a declaration of a function at block scope (that's not a using-declaration)
3) any declaration that is not a function or a function template (e.g. a function object or another variable whose name conflicts with the name of the function that's being looked up)
更准确地说,这里的using namespace A
没有引入任何声明:
引自 cppref
Using-directive does not add any names to the declarative region in which it appears (unlike the using-declaration), and thus does not prevent identical names from being declared.
最佳答案
函数调用的名称查找有两部分:
- 正常的不合格查找
- 日常事件能力
根据 N4659 [basic.lookup.argdep]/3,正常的非限定查找首先发生;如果找到正常的不合格查找,则 ADL 阶段不会继续:
- a declaration of a class member, or
- a block-scope function declaration that is not a using-declaration, or
- a declaration that is neither a function nor a function template.
在您的代码中,正常的非限定查找会找到 A::k
,如 your previous question 中所述。 .因此此代码不会发生 ADL。
关于c++ - 为什么在使用 `using directive` 时 ADL 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312461/