Operator overloading problem

div0 div0 at sourceforge.net
Fri Aug 6 14:41:42 PDT 2010


On 06/08/2010 22:24, Blonder wrote:
> Hello,
>
> this seems to work, but if I add the following
>
> 	double opBinary(string op, U) (U rhs)
> 	{
> 		static if(op == "^"&&  is(U: Group))
> 		{
> 			// do something
> 			return 42;
> 		}
> 	}
>
> because I want to write the following: double d = g^h;
> I have the same problem again.

You should only use the static if on the 2nd template parameter.
You want:

class Group {
	void	opBinrary(string op, U)(U rhs)
	if(op == "^") {
	}

	void	opBinrary(string op, U)(U rhs)
	if(op == "+") {
	}

	void	opBinrary(string op, U)(U rhs)
	if(op == "-") {
	}

	void	opBinrary(string op, U)(U rhs)
	if(op == "*") {
	}
}

Note that the 'if' is a template constraint is and part of the template 
signature; this is what stops you getting multiple matches when trying 
to determine which template to use.

You can only use the static if inside the function if all the types U 
are similar, otherwise you'll get conversion problems with return values 
and such.

 >
 > This syntax isn't very intuitive.
 >

No programming language is intuitive; they all take time to learn.
D is a big win over C++ though and well worth sticking with.

-- 
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk


More information about the Digitalmars-d-learn mailing list