Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 11:58:49 PDT 2008


On 09/05/2008, Robert Fraser <fraserofthenight at gmail.com> wrote:
> I'm sorry if this post sounds argumentative, but I disagree strongly with
> pretty much everything in this post. So no hard feelings, peace, respect,
> all that ;-P.

All is peaceful here on the newsgroup. This is just a nice, friendly
chat. Nothing has been suggested "officially", and nothing will be, if
folk here don't like the idea.


> >    to!(T)(x)
> >
> > where to! is a template function provided by std.conv (not a keyword).
> > to! already performs many conversions. Throwing in the basics like
> > to!(int)(double) would be an obvious extension.
>
>  Ick! That means another identifier that needs to be a compiler built-in

Um. No. std.conv.to!(T) already exists.

I guess what you're saying is, it's not possible to write a function
like toInt(double) if the cast operator is gone. I hadn't thought of
that. In that case, maybe it should be

    cast!(T) // lossy conversion
    to!(T) // conversion that always succeeds, or throws an exception


> And why "union", that seems like an arbitrary keyword.

It wasn't entirely arbitrary. A union /is/ a reinterpretation of bits.
It's one memory layout painted over another. (And it's a lot shorter
than "reinterpret_cast").


> >    auto!(T)(x)
>
>  How is that better than "cast(T) x;". I guess just because it creates the
> distinction?

I guess I just couldn't think of anything better. :-) D doesn't have a
word for "mutable", and C++'s "const_cast" is too long. (And also
misleading, since its primary use is to /remove/ constancy, not add
it).


>  Okay, sorry that was so negative. But it just seems that cast() works
> perfectly fine for _all_ those things right now. If what you want is safer
> casting, you can write your own templates to do that.

You can? I confess, my template writing skills aren't up to the job.
If it could be done, that would be interesting. Obviously, you'd have
to use non-reserved words for the names though.

I'm curious to know if C++'s dynamic_cast<T>, const_cast<T> are
implemented with templates. They certainly /look/ like C++ templates.



More information about the Digitalmars-d mailing list