Skip to content

Instantly share code, notes, and snippets.

@wen-long
Created July 6, 2014 09:44
Show Gist options
  • Save wen-long/bc71863a126bfecc9c2e to your computer and use it in GitHub Desktop.
Save wen-long/bc71863a126bfecc9c2e to your computer and use it in GitHub Desktop.
也被称作“克尼格查找”(Koenig lookup)

仅当对未限定名字的正常名字查找不能发现匹配的名字,ADL才被使用。这时,函数实参的数据类型相关的命名空间也被搜索。 任何数据类型的T的相关的命名空间包括:

  1. 数据类型T的结构化作用域(structural scope),这可用于定位友函数(friend functions);
  2. 数据类型T被定义所处的命名空间;
  3. 如果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
} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment