Casting away const and invariant

James Dennett jdennett at acm.org
Sun Sep 9 19:33:29 PDT 2007


Janice Caron wrote:
>> D's single cast syntax is rather a step backwards from C++.
> 
> D's single cast syntax dates from a time before there was const. If
> there's no const, you don't need a const_cast. Only with the advent of
> const in 2.0 do we start to encounter problems.

There are other problems with a single cast notation; constness
is not the only one.  Casts on numeric types fall into various
categories; pure widening casts are entirely safe, narrowing
casts between integrals types can be safe except for truncation,
casts from some integral types to suitable floating point types
are value preserving, casts from floating point values to integral
types tend to lose information and risk range errors.  Casting up
a class hierarchy (in the presence of single inheritance only) is
safe; downcasts can fail.  Converting between pointers and integral
types can often be problematic.  Even C++'s classification of
different types of cast is not as granular as I'd like, and I've
found an implicit_cast<T> to be useful while a lossless_cast<T>
has theoretical appeal.  (The absence of MI from D means that
there is less need for something akin to a full-blown dynamic_cast:
there's no cross-casting in a single-inheritance chain.)

-- James



More information about the Digitalmars-d mailing list