A fresh look at comparisons
Janice Caron
caron800 at googlemail.com
Wed Apr 16 11:27:18 PDT 2008
On 16/04/2008, Yigal Chripun <yigal100 at gmail.com> wrote:
> Someone on this thread made a very good observation: opCmp should be a
> multi-method.
> This is an excellent idea and applies to more than just opCmp.
>
> given the following classes:
>
> class A {}
> class B : A {}
>
> class C : A {}
>
> I'd suggest the following syntax for multi-methods: (taken from the
> article linked bellow)
> void func(virtual A a1, virtual A a2);
> so both a1 and a2 can also be of any subtype of A.
>
> let's look at some of the comparison variations:
> opCmp(A a1, A a2); // compare only instances of A
> opCmp(virtual A a1, virtual A a2); // will work on all subtypes
> opCmp(virtual B b1, virtual B b2); // this overrides the above more
> general function
> etc...
> I think this can provide all possible combinations needed.
But it still won't work. Watch.
class A {}
class B : A {}
class C : A {}
opCmp(A a1, A a2) { ... } /* not virtual */
B b = new B
C c = new C
if (b < c) ...
This will /still/ cast both b and c to A's, and then do A's comparison
test. That's because B and C will both implicitly cast to A.
The only difference "virtual" will make is in the following situation
class A {}
class B : A {}
class C : A {}
opCmp(virtual A a1, virtual A a2) { ... }
opCmp(B a1, C a2) { ... }
A b = new B
A c = new C
if (b < c)...
now opCmp(B,C) would be called, because it exists. But if opCmp(B,C)
did /not/ exist, then opCmp(A,A) would be called, whether it was
virtual or not. That's because "virtual" only enables polymorphism; it
doesn't disable inheritance.
The desired goal is for opCmp(A,A) /not/ to be called if opCmp(B,C)
doesn't exist. So far as I can see, mine is the only suggestion on
this thead which achieves that goal.
More information about the Digitalmars-d
mailing list