Templated operator overloading

Simen Kjærås simen.kjaras at gmail.com
Wed Aug 22 12:36:39 UTC 2018


On Wednesday, 22 August 2018 at 11:58:25 UTC, XavierAP wrote:
> When I want to have the same operator overloading code in both 
> types however, I can't make it work:

 From https://dlang.org/spec/operatoroverloading.html#binary:
"the one with the ‘better’ match is selected. It is an error for 
both to equally match."

Since both your opOpAssigns match equally, the compiler throws 
up. The solution is to add some sort of restriction:

struct S1 {
     mixin opOver;
}

struct S2 {
     mixin opOver;
}

mixin template opOver() {
     auto opOpAssign(string op, T)(T rhs)
     if (T.stringof > typeof(this).stringof) { // Here
         import std.stdio;
         writeln(this, op, rhs);
     }
}

unittest {
     S1 a;
     S2 b;
     a += b;
}


> And a final try with a global templated function instead of a 
> mixin template:
>
> /********************/
> private void opOpAssign(string op, Tthis, T)(ref Tthis that, 
> const ref T x)

This syntax would either enable the definition of operators on 
builtin types that shouldn't have them, or be perceived as 
inconsistent, so invasive operator overloading is used in D 
instead.

--
   Simen


More information about the Digitalmars-d-learn mailing list