【问题标题】:Why is Koening lookup not working here?为什么 Koening 查找在这里不起作用?
【发布时间】:2015-03-18 15:17:29
【问题描述】:

参数依赖查找说:

对于类类型的参数(包括联合),集合包括... a) 类本身 b)...

那为什么printX找不到X呢?

 #include<iostream>
using namespace std;

class A {
public:
    static const int X = 1;
};

class B {
public:
    static void printX(A a)
    {
        cout << "X is " << X << endl;
    }
};

int main(int argc, char** argv)
{
    A a;
    B::printX(a);
    return 0;
}

【问题讨论】:

标签: c++ argument-dependent-lookup


【解决方案1】:

这不是 ADL 应该做的。 ADL 适用于 unqualified 函数调用,函数首先在定义参数类型的命名空间中搜索 .

例子,

namespace N
{
      struct A {};

      void f(A const &) {}
}

N::A a;

N::f(a); //qualified function call. ADL is not needed.
f(a);    //unqualified function call. ADL works here

在上面的示例中,f(a) 从命名空间 N 调用 f()。由于f(a) 是非限定函数调用,ADL 使编译器首先在命名空间N 中搜索函数f,因为参数a 的类型在N 中定义。

希望对您有所帮助。

【讨论】:

  • 我怀疑你打算使用void f(A a) {}
【解决方案2】:

我想扩展@Nawaz 的答案,它对“集合包括... a) 类本身”的含义有所了解

一个示例程序:

#include <iostream>

void bar(int ) { std::cout << "Came to ::bar(int)\n"; }

namespace foo
{
   struct A2;
   struct A1
   {
      friend void bar(A1 const&) { std::cout << "Came to foo::bar(A1 const&)\n"; }
      friend void bar(A2 const&) { std::cout << "Came to foo::bar(A2 const&)\n"; }
   };

   struct A2
   {
   };
}

struct B
{
   friend void bar(B) { std::cout << "Came to ::bar(B)\n"; }
};

int main()
{
   foo::A1 a1;
   foo::A2 a2;
   B b;
   int i = 0;

   bar(i);   // This resolves to the only bar() in the global namespace.

   bar(a1);  // This resolves to the appropriate overloaded friend function
             // defined in foo::A1 because the scopes for looking up the 
             // function includes class foo::A1

   bar(a2);  // Error. The search for bar include foo::A2 but not foo::A1.        

   bar(b);   // This resolves to the friend function defined in B because
             // the scopes for looking up the function includes class B
}

【讨论】:

  • 谢谢萨胡。这确实让事情变得更加清晰。
猜你喜欢
  • 2013-05-16
  • 2019-02-10
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多