Self-reference in interface definition
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Tue May 15 22:06:10 PDT 2007
Jason House wrote:
> While the code below does not compile, I believe that it should be
> allowed. Requiring something that implements an interface to accept
> other objects conforming to the interface should always be allowed. The
> specific problem below makes perfect sense to disallowed for classes,
> but does not for interfaces.
>
> == test.d ==
> interface X{
> X opAssign(X);
> }
>
> == gdc output ==
> test.d:2: function test.X.opAssign identity assignment operator overload
> is illegal
The problem is specifically with the X in opAssign's parameters. One of the restrictions
on assignment operator overloading is that any type X cannot have an overloaded assignment
for X or a derivative of X. From the specs:
"""The assignment operator cannot be overloaded for rvalues that can be implicitly cast to
the lvalue type."""
Nor may an opAssign have more than one parameter.
I assume your intention was to have code like:
X x1 = new A;
X x2 = new B;
x1 = x2;
Where the assignment at the end copies data from x2 to x1 rather than making them the same
reference. For that you will need an explicit copy(X) method instead. Or maybe you
wanted something else, but that was what first came to mind.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list