array of elements of various sybtypes
Steven Schveighoffer
schveiguy at yahoo.com
Fri Jan 28 07:45:02 PST 2011
On Wed, 26 Jan 2011 23:40:39 -0500, Andrej Mitrovic
<andrej.mitrovich at gmail.com> wrote:
> On 1/27/11, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>> 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.
>
> pragma helps in discovering what DMD does sometime. This will error
> out but it will give some useful info:
>
> pragma(msg, typeid( [1,2,cast(ubyte)3] ));
> error: [1,2,cast(int)cast(ubyte)3] , &D11TypeInfo_Ai6__initZ
>
> So it forces a cast back to int again.
Right, because int can hold all of the values.
Casting the whole array to ubyte[] makes it cast all the arrays elements.
Essentially, I'm proposing that cast(U[])[e1, e2, ..., en] is translated
to [cast(U)e1, cast(U)e2, ..., cast(U)en].
This works for array literals that are composed of literal elements, but
for some reason doesn't work for classes.
>
> But we can use a postfix to set an unsigned type for the whole array:
>
> writeln(typeid( [1,2,3u] )); // uint[]
Because integer promotion rules say ints get "promoted" to uints.
Essentially, uint is considered to be able to hold all int values (even
though it technically can't). So the "common" type chosen between int and
uint is uint.
> And we can select a string type with a postfix, but we can't use a cast:
>
> void main()
> {
> writeln(typeid( ["a"d, "b", "c"] )); // works
> writeln(typeid( [cast(dchar)"a", "b", "c"] )); // doesn't work,
> // Error: incompatible types for ((cast(dchar)"a") ? ("b")): 'dchar'
> and 'string'
> }
The error has been pointed out, but you are still missing the point.
Casting one element has a partial effect on the overall type, but does not
"force" the type of the array. It only forces the type of one element.
The compiler still chooses an array type of the "common" type of all
elements.
-Steve
More information about the Digitalmars-d-learn
mailing list