test if object is instance of class at compile time
Jacob Carlborg
doob at me.com
Wed Dec 21 23:17:33 PST 2011
On 2011-12-21 21:15, 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").
>
> Moreover, in CTFE a failed cast terminates the interpretation ("cannot
> reinterpret class from [...] to [...] at compile time"). 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;
> }
> }
> ---
>
I don't think you can do a test like that during compile time. In your
above function, isInstanceOf, "o" will always be of the type "O". You
can always do a comparisons to see if O is the same type as T.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list