Comment #0 by andrej.mitrovich — 2016-09-09T15:27:52Z
The following compiles but it's known at compile-time to return null:
-----
class C { }
class D { }
void main ( )
{
auto d = new D;
auto c = cast(C)d; // compiler knows it will be null
}
-----
It's possible for a class to define opCast, however it's a templated method and so the compiler would still know if such casts make sense or not:
-----
class C
{
T opCast(T)() if (is(T == D))
{
return new T;
}
}
class D { }
void main ( )
{
auto c = new C;
auto d_from_c = cast(D)c; // ok, might work
auto d = new D;
auto c_from_d = cast(C)d; // should error
}
-----
There is a slight possibility that this affects some generic code (makes it not compile), but in such a case the code could easily be changed to use `static if (is(typeof( cast(Target)source ))).
Comment #1 by robert.schadek — 2024-12-13T18:50:00Z