Passing rvalues to functions expecting const ref

Minas Mina minas_mina1990 at hotmail.co.uk
Sun Dec 23 13:28:58 PST 2012


On Sunday, 23 December 2012 at 20:40:09 UTC, Namespace wrote:
> Minas Mina:
> Show me the whole code, I think that your opBinary functions 
> returns rvalues.
> This would be a good and important case for "auto ref". But 
> until now it is only for template paramters...

struct Vector3
{
	float x, y, z;
	
	this(float _x, float _y, float _z)
	{
		x = _x;
		y = _y;
		z = _z;
	}
	
	// negate operator
	Vector3 opUnary(string s)() const if( s == "-" )
	{
		Vector3 temp = this;
		
		temp.x = -temp.x;
		temp.y = -temp.y;
		temp.z = -temp.z;
		
		return temp;
	}
	
	// + operator for completeness
	Vector3 opUnary(string s)() const if( s == "+" )
	{
		return this;
	}
	
	// binary operators
	Vector3 opBinary(string op) (float val) const
	{
		static if( op == "+" )
		{
			Vector3 temp = this;
			temp.x += val;
			temp.y += val;
			temp.z += val;
		}
		else static if( op == "-" )
		{
			Vector3 temp = this;
			temp.x -= val;
			temp.y -= val;
			temp.z -= val;
		}
		else static if( op == "*" )
		{
			Vector3 temp = this;
			temp.x *= val;
			temp.y *= val;
			temp.z *= val;
		}
		else static if( op == "/" )
		{
			Vector3 temp = this;
			temp.x /= val;
			temp.y /= val;
			temp.z /= val;
		}
		
		return temp;
	}
	
	Vector3 opBinary(string op) (Vector3 v) const
	{
		static if( op == "+" )
		{
			Vector3 temp = this;
			temp.x += v.x;
			temp.y += v.y;
			temp.z += v.z;
		}
		static if( op == "-" )
		{
			Vector3 temp = this;
			temp.x -= v.x;
			temp.y -= v.y;
			temp.z -= v.z;
		}
		static if( op == "*" )
		{
			Vector3 temp = this;
			temp.x *= v.x;
			temp.y *= v.y;
			temp.z *= v.z;
		}
		
		return temp;
	}
}

/// dot product of two Vector3 vectors
@safe pure float dot(Vector3 u, Vector3 v)
{
	return u.x * v.x + u.y * v.y + u.z * v.z;
}

dot is making copies now because what I have shown earlier does 
not work... It's what I'm using now.


More information about the Digitalmars-d-learn mailing list