On Friday, 21 July 2017 at 23:38:51 UTC, FoxyBrown wrote:
On Friday, 21 July 2017 at 22:35:20 UTC, Era Scarecrow wrote:
On Friday, 21 July 2017 at 21:03:22 UTC, FoxyBrown wrote:
Is there a way to easily find the differences between to struct instances? I would like to report only the differences

e.g.,

writeln(s1 - s2);

prints only what is different between s1 and s2.


No, it isn't. It is a concept, wasn't mean to be taken as literal D code.

This is entirely dependent on the structs in question, you can't just subtract any struct from another struct unless it knows how to do it.

Depends on what the structures hold. You'll probably have to either make an opSub, a function to call opBinary!"-", or do opCmp which returns which is higher/lower (and may be as simple as subtraction).

Why do I want to go through all that trouble? A simple binary compare should suffice.

use opCmp in conjunction with __traits(allMembers,T)

struct Example
{
    int a,b,c;
    string d,e,f;
}

void difference(alias func, T)(T t1, T t2) if(__traits(compiles, func(t1,t2)))
{
    foreach(U; __traits(allMembers,T)
    {
if (mixin("t1." ~ U.stringof~ ".opCmp(t2." ~ U.stringof ~")")
            func(t1,t2);
    }

}

auto a =  Example(1,2,3,"foo","bar",baz");
auto a =  Example(1,2,42,"foo","bar",quux");

difference!(writeln)(a,b); // hopefully prints 343\nbazquux

Not tested but should give you an idea to adapt as needed.

Reply via email to