Thread overview | ||||||
---|---|---|---|---|---|---|
|
August 19, 2017 Using mixin templates for operator overloading. | ||||
---|---|---|---|---|
| ||||
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); } |
August 20, 2017 Re: Using mixin templates for operator overloading. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Balagopal Komarath | On Saturday, 19 August 2017 at 10:16:18 UTC, Balagopal Komarath wrote:
> Let us say I want to automatically define subtraction given that addition and negation are defined. I tried the following using mixin templates...
I assume there is no way to do this?
|
August 20, 2017 Re: Using mixin templates for operator overloading. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Balagopal Komarath | On Saturday, 19 August 2017 at 10:16:18 UTC, Balagopal Komarath wrote:
> 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
>
> [...]
Did you try changing the `: "+"` constraints to `if` constraints?
|
August 20, 2017 Re: Using mixin templates for operator overloading. | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicholas Wilson | On Sunday, 20 August 2017 at 12:46:59 UTC, Nicholas Wilson wrote:
> Did you try changing the `: "+"` constraints to `if` constraints?
Yes. Yields the same result as this.
|
Copyright © 1999-2021 by the D Language Foundation