Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
peoro Avatar asked Jan 05 '11 09:01

peoro


2 Answers

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).

like image 85
Alexandre C. Avatar answered Oct 05 '22 23:10

Alexandre C.


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

like image 28
CB Bailey Avatar answered Oct 05 '22 21:10

CB Bailey