Why does this code only work with `std.conv.to` whilst not with `cast`?
ag0aep6g
anonymous at example.com
Sun Jan 8 12:32:21 UTC 2023
On 08.01.23 12:29, thebluepandabear wrote:
> ```D
> interface ICustomDrawable {
> void render(sfRenderWindow* renderWindow);
> }
[...]> class Button : ICustomDrawable {
[...]
> }
[...]
> class StackLayout : ICustomDrawable {
[...]
> ICustomDrawable[] _children;
> }
> ```
>
> For some reason, when I want to cast the `children` (property), only the
> second example works:
>
> 1.
>
> ```D
> foreach (Button button; cast(Button[])(_boardSizeRow.children)) {
> button.update(event, _renderWindow);
> }
> ```
>
> 2.
>
> ```D
> foreach (Button button; to!(Button[])(_boardSizeRow.children)) {
> button.update(event, _renderWindow);
> }
> ```
Two things you need to know:
1. While an interface reference implicitly converts to a compatible
class reference, the resulting pointer is slightly different.
----
interface I {}
class C : I {}
void main()
{
C c = new C;
I i = c;
import std.stdio;
writeln(cast(void*) c); /* e.g. 7F3C140A7000 */
writeln(cast(void*) i); /* e.g. 7F3C140A7010 */
}
----
2. Casting from one array type to another is done "as a type paint"[1].
The elements of the array are reinterpreted, not converted.
But reinterpreting interface references as class references won't work,
because the pointers will be wrong. You need to convert each element of
the array (which is what `to` does).
[1] https://dlang.org/spec/expression.html#cast_array
More information about the Digitalmars-d-learn
mailing list