Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 03:05:17 PDT 2008


2008/5/9 terranium <spam at here.lot>:
> 1) I don't think you can throw away the cast keyword, this will break all existing code.

This is exactly the problem C++ had. C++ introduced new, better cast
types: static_cast<T>, dynamic_cast<T>, const_cast<T>, and
reinterpret_cast<T>. However, where C++ went wrong is they failed to
outlaw the original cast - presumably for the same reason, that it
would break existing code.

The problem is that unless you outlaw the old "one cast for all
purposes" cast, then people will continue to use it, when what you
really want it to force everyone to migrate to the new, "safe" ways.


> 2) how about interfaces?

They're a run-time thing, so is!(T) and class!(T) should work for
interfaces just as for classes. This is where D differs from C++, of
course, because we have interfaces where C++ has multiple inheritance.
But yeah - just as C++'s dynamic_cast<T> works for multiple
inheritance, so class!(T) should work for interfaces - though I note
that the name is now less apt.



> 3) I believe reinterpret_cast was introduced as analog of C cast,

It was introduced to replace /one/ kind of transformation which
old-style casts did, but not all of them. For example

    // C++
    double x;
    int y = reinterpret_cast<int>(x); // won't compile
    int y = static_cast<int>(x); // OK



> D already has cast for this purpose. I don't think D needs union!().

D already has cast for /all/ of the purposes I listed, so you could
argue that D doesn't need any of them. The point is, if you wanted to
be explicit about exactly what kind of transformation you wanted, then
you would need it.


> 4) D already has cast to add/remove constancy/invariance.

Again, D already has cast, which can do each and every transformation
I listed. What it can't do is emit an error if the wrong kind of
transformation is performed.


> My proposal was just adding safe cast for downcasts with the syntax of existing cast, nothing more.

I wasn't disputing that. Consider this a separate proposal.



More information about the Digitalmars-d mailing list