Koenig 查找的基本原理

发布于 2024-10-10 13:48:22 字数 119 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紧拥背影 2024-10-17 13:48:22

IIRC 最初的动机是能够

std::cout << 42;

在无需显式限定 std::operator<<(std::ostream&, int) 的情况下进行编写。

如果要禁用参数相关查找,可以显式限定函数名称,即。使用 std::swap 而不是 swap 来防止在其参数所在的任何命名空间中查找 swap

ADL 还可以与 SFINAE 一起使用,在编译时测试是否为特定类型定义了某个函数(我将让您将其作为练习,Stackoverflow 上至少有一个关于此的问题)。

The original motivation, IIRC, was to be able to write

std::cout << 42;

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 of swap to prevent swap 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).

半边脸i 2024-10-17 13:48:22

ADL 最强大的用例就是这样的情况。

namespace A
{
    struct S {};
    S operator+( const S&, const S& );
}

namespace B
{
    A::S test()
    {
        A::S a, b;
        return a + b;
    }
}

它对于在通用代码中选择正确的 swap 函数也很有用,因此它不应仅适用于 operator 函数。它已经是标准中相当复杂的一部分,制定阻止其在某些情况下工作的规则会进一步增加复杂性,这会带来什么好处?

我想不出有什么巧妙的方式来显式地请求它,这比直接调用不同名称空间中的函数要简洁得多,并且在任何情况下都会使表达式更加复杂。

您是否在想: return [[ use_adl ]] (a + b);return A::operator+( a, b );

The strongest use case for ADL is for cases like this.

namespace A
{
    struct S {};
    S operator+( const S&, const S& );
}

namespace B
{
    A::S test()
    {
        A::S a, b;
        return a + b;
    }
}

It is also useful for selecting the correct swap function in generic code so it shouldn't only apply to operator 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 ); ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文