Operators overloading

matovitch camille.brugel at laposte.net
Sun May 19 00:32:09 PDT 2013


Hello from France everyone ! (I hope my english will be 
readable...)

Yesterday, I discover D and that was really really great. I am 
far from being a guru (it seems there are a lot here ;-) but I 
foud the language clear and expressive the documentation is very 
well done futhermore dmd is incredibly fast and the logs are pure 
awesomness (a gcc command often doesn't fit on my shell). I know 
you are waiting for a 'but' and there is one : it's about 
operators overloading. First, but that kind of ok with me, I 
don't like the syntax :

	const Vertex opBinary(string op)(const ref Vertex vertex)
		if (op == "+" || op == "-")
	{
		Vertex result = *this;
		mixin("result" ~ op ~ "= vertex;");
		return result;
	}

I don't like the 'if' outside and the condition could be really 
long : if (op == "+" || op == "-" || op == "*" || op == "/"). 
Okay, putting the if inside is quite easy :

	const Vertex opBinary(string op)(const ref Vertex vertex)	
	{
		static if 	if (op == "+" || op == "-")
		{
			Vertex result = *this;
			mixin("result" ~ op ~ "= vertex;");
			return result;
		}
	}

But...I'd like to define cross product :

	const T opBinary(string op)(const ref Vertex vertex)
	{
		static if (op == "*")
		{
			T result = 0;
			foreach(i; 0..vertex_size)
				result += coordinate[i] * vertex.coordinate[i];
			return result;
		}
	}

The compiler is not so great here and doesn't distinguish the two 
opBinary by their signatures. Why ? Before looking at the 
documentation again I tried something like that :
	
	const Vertex opBinary(string op : ["+", "-"])(const ref Vertex 
vertex)	
	{
		{
			Vertex result = *this;
			mixin("result" ~ op ~ "= vertex;");
			return result;
		}
	}

	const T opBinary(string op : "*")(const ref Vertex vertex)
	{
		
		T result = 0;
		foreach(i; 0..vertex_size)
			result += coordinate[i] * vertex.coordinate[i];
		return result;
	}

The second one is okay, but the fisrt one isn't correct. I think 
this kind of template specialization over a list could be great 
with mixins and static if/switch. What do you think ? May be 
there is an other way to do what I want...


More information about the Digitalmars-d mailing list