Koenig 查找的基本原理
Koenig 查找的基本原理是什么?
无法避免将其视为使您的代码更难以阅读并且更加不稳定的东西。
难道他们不能定义 Koenig 查找,使其仅适用于特定情况(即:非成员运算符)或明确需要时吗?
What's the rationale of Koenig lookup?
Cannot avoid thinking of it like something that makes your code a lot harder to read and more instable.
Couldn't they define Koenig lookup so that it only work for specific cases (ie: non-member operators) or when explicitly required?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IIRC 最初的动机是能够
在无需显式限定
std::operator<<(std::ostream&, int)
的情况下进行编写。如果要禁用参数相关查找,可以显式限定函数名称,即。使用
std::swap
而不是swap
来防止在其参数所在的任何命名空间中查找swap
。ADL 还可以与 SFINAE 一起使用,在编译时测试是否为特定类型定义了某个函数(我将让您将其作为练习,Stackoverflow 上至少有一个关于此的问题)。
The original motivation, IIRC, was to be able to write
without having to qualify
std::operator<<(std::ostream&, int)
explicitely.If you want to disable argument dependant lookup, you can explicitely qualify the function name, ie. use
std::swap
instead ofswap
to preventswap
to be looked up in whatever namespace its arguments would live.ADL can also be used with SFINAE to test at compile time whether some function is defined for a particular type (I'll let you work this out as an exercise, there is at least one question about this on Stackoverflow).
ADL 最强大的用例就是这样的情况。
它对于在通用代码中选择正确的
swap
函数也很有用,因此它不应仅适用于operator
函数。它已经是标准中相当复杂的一部分,制定阻止其在某些情况下工作的规则会进一步增加复杂性,这会带来什么好处?我想不出有什么巧妙的方式来显式地请求它,这比直接调用不同名称空间中的函数要简洁得多,并且在任何情况下都会使表达式更加复杂。
您是否在想:
return [[ use_adl ]] (a + b);
与return A::operator+( a, b );
?The strongest use case for ADL is for cases like this.
It is also useful for selecting the correct
swap
function in generic code so it shouldn't only apply tooperator
functions. It is already a fairly complex part of the standard, making rules that prevented it from working in some cases would add further complexity, what would be the gain?I can't think of any neat way of asking for it explicitly that would be significantly less verbose than calling a function in a different namespace directly and would, in any case, make expressions more complex.
We're you thinking something like:
return [[ use_adl ]] (a + b);
vs.return A::operator+( a, b );
?