Can i rewrite methods in one line?

Ivan Agafonov armadil at yandex.ru
Sun Sep 2 20:36:31 PDT 2012


Yeah! I did it!
How about this solution? What do you think?

static assert(size >= 2 && size <= 4);
	static assert(__traits(isFloating, T));
	
	/// Vector components
	union
	{
		T[size] array = 0;
		struct
		{
			static if(size == 2) T x, y;
			static if(size == 3) T x, y, z;
			static if(size == 4) T x, y, z, w;
		}
	}

	this (T rhs)			{ array[] = rhs; }
	this (T[] components...)	{ array[] = components[]; }
	this (T* components)		{ array[] = components[0..size]; }
	this (T[size] components)	{ array[] = components[]; }
	this (Vector rhs)		{ array[] = rhs.array[]; }
	
	private static bool isMathOp(string op)
	{ return (op == "+" || op == "-" || op == "*" || op == "/"); }
	
	Vector opUnary(string op) () if (op == "-")
	{ return Vector(array.dup[] = -array[]); }

	Vector opBinary(string op) (Vector rhs) if(isMathOp(op))
	{ return Vector(mixin("array.dup[] "~op~"= rhs.array[]")); }
	
	Vector opBinary(string op) (T rhs) if(isMathOp(op))
	{ return Vector(mixin("array.dup[] "~op~"= rhs")); }

	ref Vector opAssign(Vector rhs) { array[] = rhs.array[]; return 
this; }
	ref Vector opAssign(T[size] rhs) { array[] = rhs[]; return this; 
}
	
	ref Vector opOpAssign(string op) (T[size] rhs) if(isMathOp(op))
	{ mixin("array[] "~op~"= rhs[];"); return this; }
	
	ref Vector opOpAssign(string op) (Vector rhs) if(isMathOp(op))
	{ mixin("array[] "~op~"= rhs.array[];"); return this; }
	
	ref Vector opOpAssign(string op) (T rhs) if(isMathOp(op))
	{ mixin("array[] "~op~"= rhs;"); return this; }

	... Some other op's ...
}


More information about the Digitalmars-d-learn mailing list