On Tuesday, 29 November 2016 at 09:58:16 UTC, ag0aep6g wrote:
On 11/29/2016 02:21 AM, Basile B. wrote:
The cast from a class type to a sub class in itself does
absolutely
nothing.
That can't be right. A bad downcast gives you null, so it has
to check the dynamic type information. Compare with upcasts
which are statically known to be correct, so they don't need to
check anything at runtime.
Usually casts to base classes can be determined if they're valid
at compile-time.
Take this for an example:
class Foo {
}
class Bar : Foo {
}
void main() {
auto bar = new Bar;
auto foo = cast(Foo)bar; // The compiler should know that bar
is of type Bar, which is a subclass of Foo and thus the cast
theoretically is redundant.
}
Even in a situation like this, the compiler should be able to see
if the cast could ever be invalid during compile-time determined
by calls to fun.
void fun(Cast)(Bar bar) {
return cast(Cast)bar; // If Cast is Foo then the compiler
should know the cast is redundant.
]
I don't know if the D compiler actually takes such situation into
account, but I'd assume it does some kind of optimization in
regards of that.