Operator Overloading with multiple return types

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Mar 15 22:45:52 UTC 2019


On Fri, Mar 15, 2019 at 09:35:12PM +0000, eXodiquas via Digitalmars-d-learn wrote:
[...]
> Vector opBinary(string op)(Vector rhs)
> {
>     static if (op == "+") return Vector(this.x + rhs.x, this.y + rhs.y);
>     else static if (op == "-") return Vector(this.x - rhs.x, this.y -
> rhs.y);
> }
> 
> As you can see for the dot product the return type has to be a
> float/double and not a vector. Is there any way to achive this
> behaivour with D2? The opMul() function is not D2 style and I don't
> want to use it.
[...]

Use signature constraints to declare different overloads depending on
what the operator is. For example:

	Vector opBinary(string op)(Vector rhs)
		if (op == "+" || op == "=")
	{
		... /* implement + and - here */
	}

	double opBinary(string op)(Vector rhs)
		if (op == "*")
	{
		... /* implement dot product here */
	}


T

-- 
It is widely believed that reinventing the wheel is a waste of time; but I disagree: without wheel reinventers, we would be still be stuck with wooden horse-cart wheels.


More information about the Digitalmars-d-learn mailing list