Why does this code only work with `std.conv.to` whilst not with `cast`?
thebluepandabear
therealbluepandabear at protonmail.com
Sun Jan 8 11:29:10 UTC 2023
I've been writing some code and I have been experimenting with
casting. I've found that sometimes only `std.conv.to!` does the
job over casting, and I am unsure why this is the case as I
assumed that they are both the same.
I have the following interface:
```D
interface ICustomDrawable {
void render(sfRenderWindow* renderWindow);
}
```
And the following class that implements that interface:
```D
class Button : ICustomDrawable {
...
override void render(sfRenderWindow* renderWindow) {
...
}
}
```
And this class which uses `ICustomDrawable`:
```D
class StackLayout : ICustomDrawable {
...
void addChild(T)(T child) {
static assert(is(T : ICustomDrawable), "Invalid type T
for child");
...
}
...
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);
}
```
When I run the first code example I get a black screen, whilst
with the second I do not. I find this very strange as when I
write to the console the 'type', it is the same for both
scenarios.
Help would be appreciated as to why this is happening so I can
better understand how D works.
More information about the Digitalmars-d-learn
mailing list