'Rationale for Koenig lookup

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?



Solution 1:[1]

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 ); ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Péter Török