Array literals are weird.
Blatnik
blatblatnik at gmail.com
Tue May 4 21:49:16 UTC 2021
On Tuesday, 4 May 2021 at 19:44:24 UTC, Imperatorn wrote:
> ```d
> auto a = [1,2,3] + [3,2,1]; //[4,4,4]
> ```
>
> Can this be accomplished using templates or a library solution,
> or do I have to modify the compiler?
I'm by no means a high priest of D. However I'm fairly confident
the answer to your question is no.
```D
// Built-in:
int[3] a = [1,2,3] + [3,2,1]; // You can do this.
auto a = [1,2,3] + [3,2,1]; // But not this.
// With H.S. Teoh's thing:
auto a = v(1,2,3) + v(3,2,1); // You can do this - a is int[3].
auto a = v(1,2,3) + v(3,2,1) + v(42,42,42); // But not this -
Error: Invalid array operation.
```
So if you actually want to make this universal, you would need to
modify the compiler.
From my own testing, the compiler actually turns these kinds of
expressions into a function call.
```D
int[3] a = [1,2,3] + [3,2,1];
// Gets turned into something like ..
import core.internal.array.operations;
int[3] a;
int[3] __temp1 = [1,2,3];
int[3] __temp2 = [3,2,1];
arrayOp!(int[], int[], int[], "+", "=")(a[], __temp1[],
__temp2[], "+", "=");
```
This also might explain why you can't use `auto a = ...` (it's
not a great excuse).
More information about the Digitalmars-d
mailing list