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

Denis Koroskin 2korden at gmail.com
Tue Jan 6 16:59:07 PST 2009


On Wed, 07 Jan 2009 03:49:38 +0300, Stewart Gordon <smjg_1998 at yahoo.com> wrote:

> 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:
>
>      
>
> 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.

Nice, but I don't like the proposed syntax much, especially these:

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

I believe it would be better to split them into two separate casts as follows:

BaseClass[] base = cast(BaseClass[])cast(!const)derived;




More information about the Digitalmars-d mailing list