On Friday, 11 October 2013 at 19:54:39 UTC, Jonathan M Davis wrote:
On Friday, October 11, 2013 21:19:29 luminousone wrote:
Using casts that way won't always be correct, it would be better
to use reflection in some way if possible.

The only reason that the casts wouldn't be correct would be if the class overrode opCast for the type that you're casting to or had an alias this declaration for it. Using casting for "instanceOf" is considered the standard and correct way to do it. But if you're being paranoid about the possibility of a conversion being defined with opCast or alias this, then yes, you need to
use typeid.

- Jonathan M Davis

import std.stdio;

bool instanceOf(A, B)(B value) {
        return !!cast(A)value;
}

class e {
}

class f : e {

}

class g {

}


void main() {
        int a;
        float b;
        char c;

        e E;
        f F;
        g G;

        assert( 1.instanceOf!int, "1");
        assert( a.instanceOf!int, "a"); // fails here ?!?
        assert( b.instanceOf!int, "b");
        assert( c.instanceOf!int, "c");

        assert( E.instanceOf!e  , "e"); // fails here !??
        assert( F.instanceOf!e  , "f");
        assert( G.instanceOf!e  , "g"); // fails as expected
}


Seems to be problems, at least with quick testing using rdmd. Using casts seems terribly hackish, I would think that some sort of reflection should be much safer/correct way todo this.

Reply via email to