依赖于参数的查找说:
对于类类型的参数(包括union),该集合包含... 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;
}
答案 0 :(得分:5)
这不是ADL应该做的事情。 ADL适用于非限定函数调用,该函数首先在名称空间中搜索,其中定义了参数的类型
实施例,
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)
从名称空间f()
调用N
。由于f(a)
是非限定函数调用,因此ADL使编译器能够首先搜索命名空间f
中的函数N
作为参数的类型{{1} }在a
中定义。
希望有所帮助。
答案 1 :(得分:1)
我想扩大@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
}