Thread overview |
---|
October 21, 2012 class opBinary overloading. value + null and null + value | ||||
---|---|---|---|---|
| ||||
public class MyClass { private int value; this(int val) { value = val; } MyClass opBinary(string op: "+")(MyClass rhs) { if (rhs is null) { return null; } MyClass result = new MyClass(value + rhs.value); return result; } } void main() { MyClass v1 = new MyClass(4); MyClass v2 = new MyClass(5); auto v3 = v1 + null; // v3 is null auto v4 = null + v2; // v4 equals v2 } in this example v3 is null. i thought v4 would be null too, but i was wrong. what should i do to make my binary operation commutative? |
October 21, 2012 Re: class opBinary overloading. value + null and null + value | ||||
---|---|---|---|---|
| ||||
Posted in reply to ref2401 | On Sunday, 21 October 2012 at 20:34:51 UTC, ref2401 wrote: > what should i do to make my binary operation commutative? You can overload opBinaryRight: MyClass opBinaryRight(string op: "+")(MyClass rhs) { if (rhs is null) { return null; } MyClass result = new MyClass(value + rhs.value); return result; } http://dlang.org/operatoroverloading.html |
October 21, 2012 Re: class opBinary overloading. value + null and null + value | ||||
---|---|---|---|---|
| ||||
Posted in reply to cal | On Sunday, 21 October 2012 at 20:42:08 UTC, cal wrote:
> On Sunday, 21 October 2012 at 20:34:51 UTC, ref2401 wrote:
>> what should i do to make my binary operation commutative?
>
> You can overload opBinaryRight:
>
> MyClass opBinaryRight(string op: "+")(MyClass rhs)
> {
> if (rhs is null)
> {
> return null;
> }
> MyClass result = new MyClass(value + rhs.value);
> return result;
> }
>
> http://dlang.org/operatoroverloading.html
in the following case
auto v5 = v1 + v2;
there will be compile time error:
overloads pure @safe MyClass(MyClass rhs) and pure @safe MyClass(MyClass lhs) both match argument list for opBinary
|
October 21, 2012 Re: class opBinary overloading. value + null and null + value | ||||
---|---|---|---|---|
| ||||
Posted in reply to ref2401 | On Sunday, 21 October 2012 at 20:54:15 UTC, ref2401 wrote: > On Sunday, 21 October 2012 at 20:42:08 UTC, cal wrote: >> On Sunday, 21 October 2012 at 20:34:51 UTC, ref2401 wrote: >>> what should i do to make my binary operation commutative? > in the following case > > auto v5 = v1 + v2; > > there will be compile time error: > overloads pure @safe MyClass(MyClass rhs) and pure @safe MyClass(MyClass lhs) both match argument list for opBinary Oh right, sorry. Well if all you want to do is catch the null on either side of the '+', you could use this overload of opBinaryRight: MyClass opBinaryRight(string op: "+", T)(T rhs) if (!is(T == MyClass)) { return null; } I'm not sure if this is what you are trying to do though... |
Copyright © 1999-2021 by the D Language Foundation