dsimcha wrote:
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;
}
}
Looks cool. I think a first shot would be to make it a standalone function.
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.
This can be done if you associate a cost with each operation (e.g.
comparing numbers has cost 1, comparing strings has cost 10, comparing
using a user-defined function has cost 40 etc.) and then optimize for
smallest average cost.
Andrei