ADL:它的規則就是當編譯器對無限定域的函數調用進行名字查找時,除了當前名字空間域以外,也會把函數參數類型所處的名字空間加入查找的范圍。
什么是無限定域的函數?
function(args); // 無限定域 namespace::function(args); // 有限定域
函數所在域的分類:
1:類域(函數作為某個類的成員函數(靜態或非靜態))
2:名字空間域
3:全局域
例子:
#include <iostream> using namespace std; namespace Koenig { class KoenigArg { public: ostream& print(ostream& out) const { out<<member_<<endl; } KoenigArg(int member = 5) : member_(member){} private: int member_; }; inline ostream& operator<<(ostream& out, const KoenigArg& kArg) { return kArg.print(out); } }//namespace Koenig int main() { Koenig::KoenigArg karg(10); cout<<karg; return 0; }
使用operator<<打印對象的狀態,但是ostream& operator<<(ostream& out, const KoenigArg& kArg) 的定義是處於名字空間Koenig,為什么編譯器在解析main函數(全局域)里面的operator<<調用時,它能夠正確定位到Koenig名字空間里面的operator<<?這是因為根據Koenig查找規則,編譯器需要把參數類型KoenigArg所在的名字空間Koenig也加入對operator<<調用的名字查找范圍中。
原文博客:http://blog.csdn.net/nodeathphoenix/article/details/18154275