仅当对未限定名字的正常名字查找不能发现匹配的名字,ADL才被使用。这时,函数实参的数据类型相关的命名空间也被搜索。 任何数据类型的T的相关的命名空间包括:
- 数据类型T的结构化作用域(structural scope),这可用于定位友函数(friend functions);
- 数据类型T被定义所处的命名空间;
- 如果T是结构类型,定义类型T所必须的结构类型相关的命名空间,但排除定义结构成员所必需的类型相关的命名空间。
#include <iostream>
class A{
public:
friend void fun(A a){std::cout << "Im here" << std::endl;}
friend void fun2(){std::cout << "Im here2" << std::endl;}
friend void fun3();
friend void fun4(A) {std::cout << "Im here 4" << std::endl;}
};
namespace B {
class BB
{ };
void fun4(BB b){
std::cout << "Im here B::fun4" << std::endl;
}
} // B
void fun4(B::BB b){
std::cout << "Im here ::fun4" << std::endl;
}
void fun3(){
std::cout << "Im here3" << std::endl;
}
int main()
{
fun(A()); // works ok
// fun2(); //error: 'fun2' was not declared in this scope
// A::fun2();// error: 'fun2' is not a member of 'A'
fun3(); // works ok
fun4(A());//OK
fun4(B::BB());//two fun4 is ambiguous
}