array cast should be supported corrected
Frank Benoit
keinfarbton at googlemail.com
Wed Aug 6 13:54:33 PDT 2008
BCS schrieb:
> Reply to Frank,
>
>> interface I{}
>> class C : I {}
>> C[] carray = getInstance();
>> I[] iarray = carray; // compile error
>> I[] iarray = cast(I[])carray; // runtime error (1)
>> // correct way:
>> I[] iarray = new I[carray.length];
>> foreach( idx, c; carray ){
>> iarray[idx] = c; // implicit cast
>> }
>> I use a template for doing this, but this looks so ugly. I[] iarray =
>> arraycast!(I)(carray);
>>
>> I think the D compiler should call a runtime method in (1) to do the
>> cast in a loop, instead of doing a simple type change that is not
>> working correctly.
>>
>
> this has come up before (IIRC) and the reply from Walter was that
> because the conversion is O(n) it should not be put into a cast that is
> otherwise O(1).
>
> OTOH if the cast(I[])carray is broken, that should be fixed (forbidden).
>
>
Yes it is broken by design.
When casting from class ref to interface ref the numerical value of the
reference must get an offset applied. So if the O(n) operation (the loop
above) is not made, the resulting array is not usable.
However. What is better in a template arraycast with o(n) or a cast?
The programmer always needs to know what the concequences are. With this
argumentation the string concatenation ~ should also be banned from the
language, because hidden heap allocation has always unbound execution time.
More information about the Digitalmars-d
mailing list