C++ Logo

std-discussion

Advanced search

Re: hidden friends and member functions

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Tue, 11 Oct 2022 01:40:23 +0300
On Tue, 11 Oct 2022 at 01:10, Federico Kircheis via Std-Discussion
<std-discussion_at_[hidden]> wrote:
> In fact the lambda is not even necessary
>
> void bar(const ns::foo&); bar(mf); // works
> using spoiler::bar; bar(mf); // works
> void bar(); bar(mf); // does not work, contrary to spoiler, very unfortunate
>
>
> But why does this example with operator== work without any workarounds?
>
>
> ----
> namespace ns{
> struct foo{
> friend bool operator==(const foo&, int){return true;}
> };
> }
>
> struct foo2{
> ns::foo mf;
> bool operator==(int i) const {
> return mf == i;
> }
> };
> ----
>
> I do not think there is some special rule for operator==, and yet no
> compiler complains...

Oh, it has special rules, in fact more than other operators, since it
considers rewritten candidates
nowadays, but for the general special rule for operators, see
http://eel.is/c++draft/over.match.oper#3 and
http://eel.is/c++draft/over.match.oper#7

In other words, that code works because the presence of the member
operator doesn't stop the search
for other candidates, like it does for non-operator functions. Note in
particular the bit in
http://eel.is/c++draft/over.match.oper#3.2
where it says
"otherwise, it includes the result of unqualified lookup for operator@
in the rewritten function call ([basic.lookup.unqual],
[basic.lookup.argdep]), ignoring all member functions."

That last bit, "ignoring all member functions", is what makes the
non-member build phase of operator lookup not find the member,
and then ADL kicks in.

Received on 2022-10-10 22:40:35