object - interface compatibility
BCS
BCS at pathlink.com
Tue Nov 14 09:28:35 PST 2006
Frank Benoit (keinfarbton) wrote:
> Today I had a hard lesson to learn. An iface and an object is not
> exchangeable. The reference to an object is manipulated if it is casted
> to an interface type.
>
> This happens implicit if an object is passed to a var/meth which wants
> it to be type of iface.
>
> But this does not happen implicit if you want to pass and array of
> objects. This is, because it would mean to iterate over the array, cast
> piece-wise and build a new array.
> But the consequence is, that the user of the class has to distinguish
> between class types and iface types.
>
> I wonder if this should really be in that way?
> Is this documented?
The convention from an object to an interface is unavoidable (at some
point). Making this conversion implicit would help but, could get costly.
interface I{}
class C : I{}
foo(I[] arr){}
fig(C[] arr){}
{
foo(cast(I[])arr);
}
void main()
{
C[] blah = new C[1000000];
fig(blah); // Ouch O(n) cost in a cast
}
you can neaten up code a bit with something like this:
If[] acast(If, Cl)(Cl[] arr)
{
If[] ret = new If[arr.length];
foreach(i,e;arr)
ret[i] = cast(If)arr[i];
return ret;
}
More information about the Digitalmars-d
mailing list