opEquals code generation

drug drug2004 at bk.ru
Tue Sep 19 13:18:04 UTC 2017


19.09.2017 15:38, Steven Schveighoffer пишет:
> On 9/19/17 8:01 AM, drug wrote:
>> I iterate over struct members and check against equality depending on 
>> member type. is there more simple/cleaner/better way to achieve this 
>> functionality? Especially without string mixins?
> 
> Why not just use tupleof directly instead of having to find the member 
> name and using mixins?
> 
> -Steve

Hmm, I'm sure I had tried it before and failed, but now I've managed to 
do so and it's really simpler (https://run.dlang.io/is/GJkokW):
```
auto opEquals()(auto ref const(typeof(this)) rhs)
     {
         import std.math : approxEqual, isNaN;
         import std.traits : isFloatingPoint, isIntegral;

         static foreach(i; 0..this.tupleof.length)
         {
             {
                 alias FType = typeof(this.tupleof[i]);

                 // a field of this structure
                 auto tf = this.tupleof[i];
                 // a field of other structure
                 auto of = rhs.tupleof[i];

                 static if (isFloatingPoint!FType)
                 {
                     if (!tf.isNaN || !of.isNaN)
                     {
                         if (!approxEqual(tf, of))
                             return false;
                     }
                 }
                 else static if (isIntegral!FType)
                 {
                     if (tf != of)
                         return false;
                 }
                 else
                     static assert (0);
             }
         }
         return true;
     }
```

Thank you, Steven!


More information about the Digitalmars-d-learn mailing list