Using mixin templates for operator overloading.
Balagopal Komarath via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Aug 19 03:16:18 PDT 2017
Let us say I want to automatically define subtraction given that
addition and negation are defined. I tried the following using
mixin templates. If I simply mixin the template using "mixin
sub;", then it gives the error
tmpmixin.d(29): Error: incompatible types for ((a) - (b)): 'A!0'
and 'A!0'
I found out that mixin using an identifier for template mixins
and then using an alias declaration as in the code given below
can be used to bring in overloads. But, this produces the error.
tmpmixin.d(23): Error: alias tmpmixin.A!0.A.opBinary conflicts
with template tmpmixin.A!0.A.opBinary(string op : "+")(in A
other) at tmpmixin.d(14)
tmpmixin.d(29): Error: template instance tmpmixin.A!0 error
instantiating
As you can see, there is no conflict logically. One defines
addition and the mixin defines subtraction.
What is the right way to do this?
mixin template sub()
{
alias T = typeof(this);
T opBinary(string op : "-")(in T other) const
{
return this + (-other);
}
}
struct A(int x)
{
int a;
A opBinary(string op : "+")(in A other) const
{
return A(this.a + other.a);
}
A opUnary(string op : "-")() const
{
return A(-a);
}
mixin sub ops;
alias opBinary = ops.opBinary;
}
void main()
{
import std.stdio : writeln;
auto a = A!0(5), b = A!0(6);
writeln(a-b);
}
More information about the Digitalmars-d-learn
mailing list