Comparing apples and oranges

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Sep 29 07:54:28 PDT 2009


Consider:

class Apple {}
class Orange {}

void main() {
     writeln(new Apple == new Orange);
}

This program always prints "false".  By and large, it is odd that one 
would attempt comparison between unrelated classes. I was thinking, is 
this ever legitimate, or we should just disallow it statically whenever 
possible?

The comparison would still remain possible by casting to a parent class:

     writeln(cast(Object) new Apple == cast(Object) new Orange);

I could think of rare cases in which one would want two sibling types to 
compare equal. Consider:

class Matrix { ... }
// No state added, operations optimized with BLAS
class BLASMatrix : Matrix {}
// No state added, operations optimized with LAPACK
class LAPACKMatrix : Matrix {}

Since neither derived class adds any state, both act in comparisons just 
like the base class Matrix, so it's valid to compare a BLASMatrix with a 
LAPACKMatrix.

How do you think we should go about this? Stay error-prone for the 
benefit of a few cases, or disallow sibling class comparisons statically?


Andrei




More information about the Digitalmars-d mailing list