c++ - 为什么在使用 `using directive` 时 ADL 不工作?

标签 c++

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/

相关文章:

c++ - qi::phrase_parse 返回真,即使调用了 qi::on_error

c++ - 视频处理OpenCV?

php - 关于 C++ 的一些错误

c++ - 访问被参数隐藏的数据成员

c++ - 从 C++ 中找到 "~/Library/Application Support"?

c++ - 从 Xcode 链接到 Boost

android - 在 CMake 中使用外部 C++ 库时出错

c++ - 在 C++ 中比较字符时是否需要遵循特殊语法?

c++ - std::thread 初始化构造函数给出编译错误

c++ - 图书馆项目的架构