Array literals are weird.
Q. Schroll
qs.il.paperinik at gmail.com
Tue May 4 00:06:55 UTC 2021
On Saturday, 1 May 2021 at 19:49:51 UTC, russhy wrote:
> On Saturday, 1 May 2021 at 12:22:50 UTC, evilrat wrote:
>> On Saturday, 1 May 2021 at 11:50:27 UTC, Adam D. Ruppe wrote:
>>>
>>> or you can use the library `.staticArray` thing to expressly
>>> indicate your intention on the original foo
>>>
>>> foo([1,2,3].staticArray);
>>>
>>>
>>
>> Is there one in Phobos? Anyway this works, but maybe it can be
>> made more type safe with constraints or just with improved
>> symtax.
>>
>> ```d
>> // compiles with -vgc and -betterC (weird, also without import
>> stdc.core.stdio)
>> import std.range : ElementType;
>>
>> template staticArray(alias T)
>> {
>> enum ElementType!(typeof(T))[T.length] staticArray = T;
>> }
>>
>> extern(C) void main()
>> {
>> import core.stdc.stdio;
>> auto arr = staticArray!([1,2,3]);
>> pragma(msg, typeof(arr)); // int[3]
>> foreach(i; arr)
>> printf("%d\n", i);
>> }
>> ```
>
>
> don't you realize something is weird?
>
> someone is asking to be able to do auto a = [1, 2, 3]
>
> and you propose a template?
>
> this is asking people to look for alternative language
>
> ```D
> auto a = new[1,2,3] <== this should be allocated array
> auto a = [1,2,3] <== this should be static array
> ```
>
> let's fix that, shall we? instead of telling people to bloat
> their files with templates
I agree that the non-obvious allocation is kind of a problem and
`new [ 1, 2, 3 ]` would be more explicit, but where I see the
actual issue isn't where you think it is. In `@nogc` code, the
compiler tells you that an allocation takes place and you look
for solutions to avoid it (there are multiple approaches, but no
general one).
More information about the Digitalmars-d
mailing list