Possible D2 solution to the upcasting array problem, and a related problem with const and nested arrays

Stewart Gordon smjg_1998 at yahoo.com
Tue Jan 6 16:49:38 PST 2009


Stewart Gordon wrote:
<snip>
> These unsafe conversions could still be allowed by explicit casts, 
> should they be needed for something, IWC you'd be expected to know what 
> you're doing.
<snip>

Just thinking about it, I wonder if this would be a good time to 
reconsider Janice's 1⅓-year-old proposal for preventing accidental 
casting away of const or invariant.  Without it, my proposal would leave 
open some cases where you really want an explicit cast, but not an 
unsafe one.  This applies both to casting DerivedClass[] to BaseClass[] 
and to such things as int[][] to const(int)[][].

In what follows, I will describe how it would work in conjunction with 
the implicit conversion rules I have already proposed.  Casting away 
const and casting away invariant would work in the same way, but I will 
describe it in terms of const.  (cast(!const) will probably still do for 
this, no need for cast(!invariant) as a distinct concept.)


There could be two forms of the proposed !const notation, which would 
become the only legal ways of casting away const.

     cast(!const)

would discard all levels of constancy from the type, but otherwise leave 
the type unchanged.

     cast(!const int[][])

would convert something to an int[][], obeying the usual type conversion 
rules except that any constancy in the original type is ignored.  Similarly,

     cast(!const BaseClass[])

would be the legal way to convert a DerivedClass[] to a BaseClass[], if 
that's what you really want.

Perhaps !const could be combined with const and invariant type modifiers 
within the type:

     cast(!const const(int)[][])

would cast a const(int[])[] or an int[][] to a const(int)[][].

I'm not sure whether it should be legal to use the bracket notation with 
!const

     cast(!const(const(int)[])[])

but it might be of use, e.g.

     cast(!const(int[])[][])

to ensure that const is cast away only from a certain level down - the 
cast would be illegal if const or invariant is specified at a higher 
level.  So this cast would convert either const(int)[][][] or 
const(int[])[][] to int[][][], but be illegal on const(int[][])[].  But 
I'm not sure whether this little detail has enough practical use to be 
worth it....


Comments?

Stewart.



More information about the Digitalmars-d mailing list