array of elements of various sybtypes

Steven Schveighoffer schveiguy at yahoo.com
Wed Jan 26 20:05:48 PST 2011


On Wed, 26 Jan 2011 22:10:58 -0500, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Wednesday 26 January 2011 18:59:50 Steven Schveighoffer wrote:
>> On Wed, 26 Jan 2011 18:28:12 -0500, Jonathan M Davis  
>> <jmdavisProg at gmx.com>
>>
>> wrote:
>> > I believe that it's supposed to take the common type of t1 and t2 and
>> > make the
>> > result an array of that type. So, assuming that the common type is T0,
>> > then it
>> > should work. However, it's not currently implemented that way. You  
>> could
>> > always
>> > create a bug report so that it doesn't get lost (assuming that no such
>> > report
>> > already exists).
>>
>> Object could also be the common type.  When there exists multiple
>> possibilities, and none of the possibilities are types being passed to  
>> the
>> array literal, I think it just gives up (D usually gives up in the face  
>> of
>> ambiguity, instead of possibly making the wrong decision).
>>
>> But the problem here appears that there is no way to *force* it to make
>> the right decision.
>>
>> I'd like to see cast(T0[])[...] work, I think that should solve the
>> problem.
>
> It probably doesn't for the exact same reason that the assignment didn't  
> do it.
> The expression is evaluated and _then_ it's cast. So, if the expression  
> isn't
> valid in and of itself, it fails.

This works:

cast(ubyte[])[1,2,3] // creates an array of 3 ubytes

So clearly cast has an effect on the type of the array literal in that  
case.  I'm not sure why this works and the other doesn't, but we  
definitely need something that allows one to control the array type of a  
literal.

In D1, the array could be typed by casting the first element (the first  
element was always used as the type of the array).  In D2 we no longer can  
control the type of the array that way, we need some way to do it.

It probably can be done in the case of classes by casting an element to  
the desired type, but it seems rather hoaky to require two different  
methods of typing an array literal depending on what kinds of data are in  
the array.  Plus, casting one element does not mean another element  
doesn't override it.  It's better IMO to say "I want this array to be  
T0[]" and let the compiler fail if it can't cast all the elements rather  
then have the compiler do "oh, one of these is Object, so I'm actually  
going to re-type this as Object[]".

-Steve


More information about the Digitalmars-d-learn mailing list