array of elements of various sybtypes
Steven Schveighoffer
schveiguy at yahoo.com
Fri Jan 28 07:53:58 PST 2011
On Thu, 27 Jan 2011 08:33:05 -0500, spir <denis.spir at gmail.com> wrote:
> On 01/27/2011 05:05 AM, Steven Schveighoffer wrote:
>> 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>
>>>>
>>>>
>>>> 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,
> [1,2,3] is valid! [t1,t2] is not if one of the elements' type is not
> implicitely convertible to the other. In your example cast applies to an
> already constructed array. (Hope you see what I mean)
I do, but what do you think the binary value of the array is? You might
be surprised that it is
01h 02h 03h
instead of the binary representation of the int[] [1, 2, 3]:
01h 00h 00h 00h 02h 00h 00h 00h 03h 00h 00h 00h
i.e. all the elements are casted to ubyte *before* the array is
constructed. This is the behavior I think we should have in all cases.
>> but we definitely need
>> something that allows one to control the array type of a literal.
>
> Yop! But this hint has to belong to the literal notation syntax itself.
> Not anything (like cast ot to!) that applies afterwards.
IMO cast is fair game, because it's a compiler internal operation. to! is
a library function, and should not affect the literal type.
>> 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.
>
> Works in D2. If any element is of the inteded common type, then all goes
> fine.
But this doesn't work to "force" the array type. It only works to force a
different type into consideration for the common type.
It is specifying a different intention to the compiler than I think you
want. If, for example, you *wanted* the type of the array to be T0[], and
not Object[], this line still results in an Object[] array:
Object o = new T1;
auto arr = [cast(T0)t1, t2, o];
So wouldn't you rather the compiler say "hey, o can't be a T0, even though
you want a T0[]" or would you rather it just happily carry out your order
and fail later when you try T0 methods on any of the elements?
-Steve
More information about the Digitalmars-d-learn
mailing list