www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - class opBinary overloading. value + null and null + value

reply "ref2401" <refactor24 gmail.com> writes:
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?
Oct 21 2012
parent reply "cal" <callumenator gmail.com> writes:
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
Oct 21 2012
parent reply "ref2401" <refactor24 gmail.com> writes:
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
Oct 21 2012
parent "cal" <callumenator gmail.com> writes:
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...
Oct 21 2012