Dynamic and Static Casting

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Thu Feb 10 03:54:02 PST 2011


On Thu, 10 Feb 2011 16:44:12 +0530, d coder wrote:

> Greetings All
> 
> 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.
> 
> 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?

Here's one solution.  I am not 100% sure of the validity of this, so 
until someone else vouches for it, it should be considered evil.  It 
works by first casting the reference to a pointer, then to a different 
pointer type (which goes unchecked), and then to a reference again.

    // Evil hack to emulate static_cast
    T staticCast(T, F)(F from)
    {
        return cast(T) cast(T*) cast(F*) from;
    }

Example usage:

    class A { int i; }
    class B : A { int j; }

    void main()
    {
        auto b = new B;
        b.i = 123;

        auto a = staticCast!A(b);
        assert (a.i == 123);
    }

-Lars


More information about the Digitalmars-d-learn mailing list