test if object is instance of class at compile time

Timon Gehr timon.gehr at gmx.ch
Thu Dec 22 05:35:57 PST 2011


On 12/21/2011 09:15 PM, Elvis Maehren wrote:
> This works fine at runtime, but explodes in CTFE:
> ---
> bool isInstanceOf(T, O)(O o) {
> 	return (cast(T) o) !is null;
> }
> ---
>
> CTFE doesn't like "!is null" ("cannot compare [...] at compile time").
>

This will be fixed in the next release:

http://d.puremagic.com/issues/show_bug.cgi?id=7143

> Moreover, in CTFE a failed cast terminates the interpretation ("cannot
> reinterpret class from [...] to [...] at compile time").

I don't think this is filed already. Maybe you want to file a bug report?

> Is this somehow
> catchable? If so, I could do something along these lines:
> ---
> if(__ctfe) {
> 	try {
> 		auto t = cast(T) o;
> 		return true;
> 	} catch {
> 		return false;
> 	}
> }
> ---
>

use traits(__compiles, {...}), where '...' is the exact code that fails. 
But that is a mere workaround. What you are doing should/will work.


More information about the Digitalmars-d-learn mailing list