Cannot cast X to Y at compile time...?

Timon Gehr timon.gehr at gmx.ch
Fri Mar 21 04:56:42 PDT 2014


On 03/21/2014 06:12 AM, Kapps wrote:
> On Thursday, 20 March 2014 at 21:32:08 UTC, dnspies wrote:
>> Sorry, I don't understand.  When I cast something to the wrong
>> type, I should just get a null reference, shouldn't I?  It
>> shouldn't throw an error.
>
> If the compiler can statically determine that the cast is invalid you
> get an error instead.

No.

class C{}
class D{}

void main(){
     C c=new C;
     D d=cast(D)c; // no error
     assert(c !is null);
     assert(d is null);	
}

(In any case, his problem is that the cast fails in CTFE.)

> You can use something like 'static if(is(T :
> Foo))' to test at compile-time if T is implicitly convertible to Foo
> (I'm not certain the exact semantics) or 'static
> if(is(typeof(cast(Foo)T.init)))'.
>
> There's probably better ways to do it, and I recommend asking on D.learn
> to figure out how to do what you're looking for.
>

I guess it might be a compiler bug, but it is hard to tell lacking a 
complete example.


More information about the Digitalmars-d mailing list