#include <iostream>
/*
//版本1:
namespace N{
class B{};
void f(B& b){ std::cout << "void N::f(B&)" << std::endl;}
};
N::B b;
void main(){
f(b);
}
*/
/*
//版本2:
namespace N{
class B{};
void f(int a){ std::cout << "N::f(int a)" << std::endl;}
};
N::B b;
void main(){
f(10);
}
*/
//编译出错。找不到f这个标识符。善于动脑子的人问题就来了:为什么版本1就没有这个问题呢?
//因为版本1使用Koening查找技术。利用f(b)的实际参数b所在的名字空间,得知需要查找N名字空间的f。
//此技术的大名是:ADL(argument-depentment lookup)
//问题又来了:为什么Koening要发明这个东西呢?我写N::f(10)或者using N::f;也能解决问题呀!
//版本3:
namespace N{
class B{};
B operator+(B& l, B& r){ return B() ; }
};
void main(){
using N::B;
B b1,b2;
//假设没有ADL技术,世界时这样的
//B b = N::operator+(b1,b2);
//或者
//using N::operator+;
//而现实是更便利的语法
B b = b1 + b2 ;
}
//总结:要像成员函数调用语法一样便捷,发明了ADL技术。
// b.f(); //无需指出f处于哪个名字空间,即 b.B::f()这样的怪物。
// f(b); //普通函数也能做到这一点。
咬文嚼字之:ADL 和 Koening
最新推荐文章于 2018-04-19 17:09:01 发布