其他分享
首页 > 其他分享> > c普通查找与参数依赖查找

c普通查找与参数依赖查找

作者:互联网

考虑http://en.cppreference.com/w/cpp/language/adl中描述的此示例:

namespace A {
      struct X;
      struct Y;
      void f(int);
      void g(X);
}

namespace B {
    void f(int i) {
        f(i);   // calls B::f (endless recursion)
    }
    void g(A::X x) {
        g(x);   // Error: ambiguous between B::g (ordinary lookup)
                //        and A::g (argument-dependent lookup)
    }
    void h(A::Y y) {
        h(y);   // calls B::h (endless recursion): ADL examines the A namespace
                // but finds no A::h, so only B::h from ordinary lookup is used
    }
}

我想知道为什么出现歧义,因为如果不考虑ADL规则

“the lookup set produced by usual unqualified lookup contains any of the following”.

根据规则,这里可以通过非限定查找找到B :: g,如http://en.cppreference.com/w/cpp/language/unqualified_lookup中所述

For a name used in the definition of a function, either in its body or as part of default argument, where the function is a member of user-declared or global namespace, the block in which the name is used is searched before the use of the name, then the enclosing block is searched before the start of that block, etc, until reaching the block that is the function body. Then the namespace in which the function is declared is searched until the definition (not necessarily the declaration) of the function that uses the name, then the enclosing namespaces, etc.

那么我的问题是为什么在这种情况下考虑ADL规则?

解决方法:

完整的报价是

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)

这意味着只有当非限定查找产生上述三个结果之一时,才会忽略ADL.由于我们没有处理类成员,因此该函数在命名空间范围内声明,而不是块作用域,我们只查找继续使用的函数并使用ADL.

标签:name-lookup,c,argument-dependent-lookup
来源: https://codeday.me/bug/20190727/1551473.html