Tuples and array literals
Jari-Matti Mäkelä
jmjmak at utu.fi.invalid
Wed Mar 7 01:32:35 PST 2007
Daniel Keep kirjoitti:
>
> Jari-Matti Mäkelä wrote:
>> I tried to search the ng and dstress test cases, but there was nothing
>> about these.
>>
>> So here are the working ones:
>>
>> const a = [1,2];
>> int[] b = [1,2];
>>
>> struct foo {
>> const int[] c = [1,2];
>> const d = [1,2];
>> }
>>
>> void main() {
>> const e = [1,2];
>> }
>>
>> These ones don't work:
>>
>> template Tuple(E...) { alias E Tuple; }
>> alias Tuple!(0,1) TP;
>>
>> const a = [ TP ];
>> int[] b = [ TP ];
>>
>> struct foo {
>> const int[] c = [ TP ];
>> const d = [ TP ];
>> }
>>
>> So, are these going to be fixed in future releases or is there some
>> serious limitation in the template/tuple system that prevents any of
>> these? Any workarounds that make use of tuples?
>
> I'm not an expert on Tuples, but I don't think you can alias expression
> tuples like (0,1), for the same reason you can't alias 1 or 2.
I'm not an expert either. I found the aliasing from
http://www.digitalmars.com/d/tuple.html.
"Expression Tuples
If a tuple's elements are solely expressions, it is called an
ExpressionTuple."
"It can be used to create an array literal:
alias Tuple!(3, 7, 6) AT;
...
int[] a = [AT]; // same as [3,7,6]"
---
I forgot to mention that in the code I sent b) actually works, but a)
doesn't:
template Tuple(E...) { alias E Tuple; }
alias Tuple!(0,1) TP;
const a = [ TP ]; // example a)
void main() {
static const b = [ TP ]; // example b)
}
I have used code similar to b) a lot to precalculate tables in my code.
I was just curious about the actual reasons to deny the use of a).
AFAIK, it can be calculated in compile time and there is also evidence
that the tuple in a literal syntax works elsewhere.
Something like
template Tuple(E...) { alias E Tuple; }
alias Tuple!(0,1) TP;
const a = [ TP[0], TP[1] ];
also works, but the tuples really should have variable length in my code.
>
> The solution is the same: put it in a constant.
>
> typeof(Tuple!(0,1)) TP = Tuple!(0,1);
Ok, I have to try this. Thanks. My first impression is that it does not
work :)
test.d(2): Error: forward reference to type (int, int)
test.d(2): Error: cannot implicitly convert expression (tuple(0,1)) of
type (int, int) to (int, int)
Error: cannot cast int to (int, int)
More information about the Digitalmars-d-learn
mailing list