Struct Comparison

dsimcha dsimcha at yahoo.com
Thu Oct 22 07:19:41 PDT 2009


Regarding recent discussions in Bugzilla:  I wonder if we could somehow define
a super-efficient struct opEquals that performs introspection and only tests
expensive members if it's necessary.  For example, here is a simple case of it:

enum opEqualsMixin = q{
    bool opEquals(typeof(this) rhs) {
        foreach(tupleIndex, elem; this.tupleof) {
            static if(isIntegral!(typeof(elem))) {
                 // Compare integers first.  They're cheap.
                 if(elem != rhs.tupleof[tupleIndex]) {
                     return false;
            }
        }

        foreach(tupleIndex, elem; this.tupleof) {
            static if(isFloatingPoint!(typeof(elem))) {
                 // Compare floats.  They're also cheap.
                 if(elem != rhs.tupleof[tupleIndex]) {
                     return false;
            }
        }

        foreach(tupleIndex, elem; this.tupleof) {
            static if(!isIntegral!(typeof(elem)) &&
                !isFloatingPoint!(typeof(elem))) {

                 // All the cheap elements were equal.
                 // Resort to more expensive comparisons.
                 if(elem != rhs.tupleof[tupleIndex]) {
                     return false;
            }
        }

        return true;
    }
}

Of course, we could get even fancier.  We could recursively introspect struct
types and use various heuristics to calculate the optimal comparison order at
compile time.  Similar stuff could be done for a generic opCmp that gives a
struct an arbitrary total ordering as long as all of its members have a total
ordering.



More information about the Digitalmars-d mailing list