On Fri, Apr 5, 2024 at 12:42 PM Saki Takamachi <s...@sakiot.com> wrote:
> > The only solution I can think of at the moment is to impose the constraint > that when computing operator overloading, if the operands are both objects, > they must be of the exact same class. > > When calculating using a method, it is clear which object should be > prioritized, so there is no risk of breaking down even if the method > accepts objects of different classes as arguments. It would be possible to > unify the behavior of the methods with operator overloading, but this would > be undesirable because the arguments would be contravariant. > > This is something that there are established solutions for actually. It's called Polymorphic Handler Resolution. This essentially means that when you have two objects used with operators, if they share a parent class or a class structure, the newest descendant is given priority. For example, if you have class A as the parent, then class B and class C as children: A + B = B, because it is a child class of A B + A = B, because it is a child class of A B + C = B, because neither are direct descendants C + B = C, because neither are direct descendants If we add the requirement that they must either be the same class as you suggested, OR one must be a descendant of the other, then we eliminate the B + C issue entirely, which makes sense for a BCMath object. How this would actually be implemented in C is that both operands would be checked for inheritance. If they are different classes and one is not the descendant of the other, it would error. If they are different classes and one IS the descendant of the other, then the handler for the descendant would be called, and that handler would always return an instance of itself. Jordan