Dynamic and Static Casting

bearophile bearophileHUGS at lycos.com
Thu Feb 10 04:05:26 PST 2011


d coder:

> I have learnt that D has only one casting operator and that is 'cast'.
> The same operator assumes different functionality depending on the
> context in which it he being used.

Walter likes this design, I presume he thinks it's simpler.


> Now I have a situation where I have to downcast an object and I am
> sure of the objects type and thereby I am sure that the downcast would
> only be successful. To make the operation faster, in C++ I could have
> used static_cast operator, thus giving the RTTI a skip. Would this be
> possible in D? Can I force a static_cast which downcasting?

There is no direct support for it because it's considered bad, so this is usually not done in D, it's for special situations only:


class Foo {}
class Bar : Foo {}
Bar test1() {
    Foo f = new Foo;
    Bar b = cast(Bar)f;
    return b;
}
Bar test2() {
    Foo f = new Foo;
    Bar b = cast(Bar)cast(void*)f;
    return b;
}
void main() {}


DMD 2.051, -O -release -inline:

_D4test5test1FZC4test3Bar   comdat
L0:     push    EAX
        mov EAX,offset FLAT:_D4test3Bar7__ClassZ
        mov ECX,offset FLAT:_D4test3Foo7__ClassZ
        push    EAX
        push    ECX
        call    near ptr __d_newclass
        add ESP,4
        push    EAX
        call    near ptr __d_dynamic_cast
        add ESP,8
        pop ECX
        ret

_D4test5test2FZC4test3Bar   comdat
L0:     push    EAX
        mov EAX,offset FLAT:_D4test3Foo7__ClassZ
        push    EAX
        call    near ptr __d_newclass
        add ESP,4
        pop ECX
        ret

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list