Default implementation of class .opEquals?

Steven Schveighoffer schveiguy at gmail.com
Thu Apr 16 17:32:45 UTC 2020


On 4/16/20 1:21 PM, H. S. Teoh wrote:
> Just out of curiosity, is there a mixin template or something like that
> in Phobos for implementing a default .opEquals that does member-wise
> comparison of a class object? Something like this:
> 
> 	mixin template DefaultOpEquals(T) {
> 		bool opEquals(Object o) {
> 			auto t = cast(T) o;
> 			if (t is null) return false;
> 			foreach (field; __traits(getAllMembers, T)) {
> 				if (this.field != t.field) return false;
> 			}
> 			return true;
> 		}
> 	}
> 
> It's annoying to have to write an .opEquals method for every class that
> basically just does the same thing.
> 

This used to work:

this.tupleof == t.tupleof;

But you may have to use std.traits or something to get in all the base 
class fields.

-Steve


More information about the Digitalmars-d mailing list