Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument-dependent lookup in C++

How does this work? Is it related to ADL?

#include <iostream>

template <typename T>
struct A
{
    friend void f(T x)
    {
        std::cout << "A\n";
    }
};

int main()
{
    f(new A<void*>());
}

Can somebody tell me why i can't use something like

f(A<int>());
like image 815
FrozenHeart Avatar asked Sep 05 '12 04:09

FrozenHeart


1 Answers

f(new A<void*>());    

Indeed works because of Argument dependent lookup/Koenig lookup(ADL)
Koenig Lookup states:

You don’t have to qualify the namespace(scope) for functions if one or more argument types are defined in the namespace of the function.

Consider a simplistic example not using templates and it should help you understand ADL at work better:

#include <iostream>
struct A
{
    friend void f(A x)
    {
        std::cout << "A\n";
    }
};

int main()
{
    f(A());
    return 0;
}

Output:

A

When you use f(A<int>()), it mandates that f() requires an argument of the type int, but your structure does not provide any conversion from A to int and hence the error.

If you provide the appropriate conversion then it will work as well. Something like:

operator int(){return 1;}
like image 181
Alok Save Avatar answered Nov 05 '22 07:11

Alok Save