Safer casts

Leandro Lucarella llucax at gmail.com
Mon May 12 10:07:46 PDT 2008


Janice Caron, el  9 de mayo a las 09:15 me escribiste:
> (*) Use RTTI to cast up and down the class heirarchy. In C++, this
> would be dynamic_cast<T>(x). For D, I suggest two things. Firstly, the
> cast:
> 
>     class!(T)(x)
> 
> to do that actual upcast or downcast - but RTTI dynamic casts can
> fail, so the question arises: What should we do if the cast fails?
> Should we return null, or should we throw an exception. My view is
> that we should throw an exception, but also introduce a new construct
> to test whether or not the cast would be possible in the first place:
> 
>     is!(T)(x)

I don't think it's a good idea, because you end up doing the RTTI check
twice this way. I think class!(T)(x) (I don't like the name but that's
another issue) should return null in case of failure. If you want it to
throw an exception, just wrap it with enforce[1]:

    enforce!(class!(T)(x))

This have been discussed recently, but this way it's more efficient (and I
think more clear and less typing):

    void f(A a)
    {
        if (B b = class!(B)(a))
        {
            /*...*/
        }
        else if (C c = class!(C)(a))
        {
            /*...*/
        }
    }

[1] http://www.digitalmars.com/d/2.0/phobos/std_contracts.html

> (*) Reinterpret a bit pattern. In C++, this would be
> reinterpret_cast<T>(x). Without changing the memory layout, or the
> constancy, reinterpret the bits to mean something else. For D, I
> suggest
> 
>     union!(T)(x)
> 
> 
> (*) Change const to mutable, or invariant to mutable. In C++, this
> would be const_cast<T>(x). There is no equivalent in D, however, in D,
> one can currently write cast(T)x, and constancy will be magically (and
> dangerously) waved away. In the new scheme, I suggest:
> 
>     auto!(T)(x)

I think this 2 can be merged toguether and called horrible_cast in honour
to Don Clugston's "Member Function Pointers and the Fastest Possible C++
Delegates" article [2] =)

[2] http://www.codeproject.com/KB/cpp/FastDelegate.aspx

-- 
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
For me to ask a woman out, I've got to get into a mental state like the karate
guys before they break the bricks.
	-- George Constanza



More information about the Digitalmars-d mailing list