Temple
Temple

Reputation: 1631

ADL of class itself

According to standard argument dependent lookup adds to search set class if we have class type as function argument:

If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes.

If so why foo cannot be found in this context:

class X{
public:
void foo(const X& ref){std::cout<<"Inner class method\n";}
};

int main(){
X x;
foo(x);
}

Shouldn't adp add to search set X class and look for foo in there?

Upvotes: 1

Views: 85

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

foo isn't a free function, it is a class method so you need to call it from an instance of your class

X a;
X b;
a.foo(b);

Note that ADL is used here so you don't have to write out the following, which would also compile fine, but is unnecessarily verbose due to ADL

a.X::foo(b);

Upvotes: 2

TartanLlama
TartanLlama

Reputation: 65590

No, because foo is a member function, not a free function which can be found through ADL.

Perhaps you means this:

static void foo(const X& ref){std::cout<<"Inner class method\n";}

This also would not be found through ADL; you would need to qualify the call like X::foo(b).

The clauses about associated classes are for friend functions declared in a class. For example:

class X{
public:
    friend void foo(const X& ref){std::cout<<"Inner class method\n";}
};

foo is a non-member function, but it can only be found through ADL.

Upvotes: 5

Related Questions