safer casts - take II

Yigal Chripun yigal100 at gmail.com
Tue May 13 11:26:51 PDT 2008


Paul D. Anderson wrote:
> Yigal Chripun Wrote:
> 
>> there are there forms of cast: (a) cast(T)something (b)
>> cast!(T)something (c) reinterpret_cast!(T)
>> 
> 
>> questions?
> 
> My only concern is the re-use of '!'.
> 
> My first thought on reading your proposal was that 'cast!(T)' was
> some sort of template. I'm sure with a little practice I could get to
> where I immediately recognize it as a dangerous(!) cast, but it's
> just one more thing to learn.
> 
> From my cursory examination of keyword usage I've concluded that the
> keywords that are problematic ('const', 'enum') are the ones that
> mean different (but related) things in different usages. I'm not at
> all convinced that parsimony in keywords is a good thing, but that
> seems to be a minority view (and it isn't Walter's view, as far as I
> can tell).
> 
> We're a little more accustomed to re-definition of symbols,
> especially in a new context, but this isn't new -- it's a variable
> name followed by a '!'.
> 
> Having said that, I don't have an alternative notation. Perhaps a
> long keyword llike 'const_cast', 'invariant_cast', etc., similar to
> the 'reinterpret_cast' usage.
> 
> I do think it's a good idea, though to have the separate types of
> casts called out.
> 
> Paul

to my defense, I'll note the fact that c++ provides its casts (except of
course the legacy C syntax) with a template syntax too, even though they
 don't have to be implemented in terms of templates. You can ask Walter
how it's implemented in DMC. and it has some similarity in meaning as
well, in a way it does behave like a template since the output is
parametrized on the input type T. even though the cast isn't really a
template, i think that both meanings are suitable here.
look at it like this:
cast(T) has similarities with a function in that it's make runtime
checks for an RTTI cast for example, or behaves like a function that
converts a value to a different type.
the cast!(T) on the other hand is more in the realm of the static world
of the compiler. it doesn't do all the checks the cast(T) does and in a
way is more low-level.

the reinterpret cast is a special case. it's very unsafe and very
low-level and I wouldn't even provide it at all in the proposal since
the experienced OS writer (as an example) which needs this feature can
implement it himself via unions. the only benefit of providing it in the
library is to have a standardized name for it. it should be discouraged
and accompanied with warnings in the docs. since D is a Systems
programming language, it's still possible to use it, only you need to be
damn sure you know what you're doing when subverting the type system
like that.



More information about the Digitalmars-d mailing list