C++ Logo

std-discussion

Advanced search

Re: Access level for defaulted comparison operators

From: Richard Hazlewood <contact.hazlewood.mail_at_[hidden]>
Date: Sat, 27 Nov 2021 13:46:18 +0000
>> ... yes. That's what you *asked* for when you made it protected. You
>> stated that code outside of the derived hierarchy of classes
>> You> cannot
>> call it.
>>
>> This includes `main`.
> I don't think the question was aimed at the commented out code. For
> some reason the base operator seem to be inaccessible even within D,
> when operator== is defaulted there.

Yes, thanks for clarifying.


> https://godbolt.org/z/sxaW5GWTn
>
> The problem seem to stem from that the defaulted operator== is defined
> in terms of (lhs_i == rhs_i && ...) for each subobject. But you can't
> call a protected member function on only arguments of base type.
> Writing the operator== manually in the equivalent way fails too:
>
> https://godbolt.org/z/Evcf6K8Yv

I guess historically there's no distinction, so it's understandable that
it might be "looking for" the free functions - outside of the hierarchy.

I notice you compiled with the trunk gcc. The `constexpr` case is no
longer accepted, so at least that can be discarded as a "blip".

> Manually it can be worked around like this:
>
> https://godbolt.org/z/b4oz5T6h9

Nice. It shows there's visibility in there somewhere.

Of course, one aim of this is to reduce the maintenance effort when
extending the classes. Taking your example, one possible kludge:

https://godbolt.org/z/48ET8h5rG

But it feels like the rules are a bit chaotic. The compiler even
accepts `struct D` declaring `using B::operator==`, but that has zero
effect (AFAICT).

> However defaulted assignment doesn't seem to suffer from this problem,
> although the situation is similar:
>
The thing with assignment is that "available" is/was always the default
(when possible). So `struct D` could be empty, and it would still do
the "right thing".

With the comparison operators, setting the base as default does not
cascade through the hierarchy - hence the need to be explicit at every
level.

There's scope for a nice compiler warning here: "base has comparison,
but derived class does not".

> The standard doesn't seem to specify how the base subobjects are
> assigned (via operator or the above function call notation from the
> context of the derived class).
>
Yes, I did have a cursory look through but couldn't find anything explicit.

Regards..

Received on 2021-11-27 07:46:22