Operator overloading problem
div0
div0 at sourceforge.net
Fri Aug 6 13:37:49 PDT 2010
On 06/08/2010 21:08, Blonder wrote:
> Hello, I am trying to understand how operator overloading works with D. I am a C++
> programmer and I am reading the book of Andrei Alexandrescu and try to understand
> D and it's language features.
>
> My Group example don't compile, the error is:
> Error: template instance opBinary!("+") matches more than one template
> declaration, ...
>
> I know that it matches more than one, that was my intention, because I want to be
> able to write also
>
> h = g+2 for example.
>
> Is this possible in D?
> Can you help me?
> Thanks,
> Andreas.
You need to add a second template parameter for the function arguments
and add a template constrait like so:
struct Group {
int i1;
Group opBinary(string op, U) (U x)
if(op == "+" && is(U: int))
{
// do somehting
return this;
}
Group opBinary(string op, U) (U rhs)
if(op == "+" && is(U: Group))
{
// do something
return this;
}
}
void main() {
Group g, h;
g.i1 = 1;
h = g+g;
}
Personally, I'm with you and I would expect that the compiler should
example the function parameters after the template string parameter but
it doesn't.
It's important to note: you must use the template parameter U, you can
not explitictly use the type (int/Group) like you can in C++.
ie you can't do:
struct Group {
int i1;
// DOES NOT WORK
Group opBinary(string op, U) (int x)
if(op == "+" && is(U: int))
{
// do somehting
return this;
}
// DOES NOT WORK
Group opBinary(string op, U) (Group rhs)
if(op == "+" && is(U: Group))
{
// do something
return this;
}
}
--
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk
More information about the Digitalmars-d-learn
mailing list