ADL(C++参数依赖查找)

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

posted on 2018-03-19 10:04  GnibChen  阅读(2256)  评论(0编辑  收藏  举报