Tuple [] operator
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 8 12:55:38 PDT 2011
On Mon, 08 Aug 2011 15:47:36 -0400, Christian Manning
<cmanning999 at gmail.com> wrote:
> Philippe Sigaud wrote:
>
>> Hi Chris,
>>
>>> import std.typecons;
>>> void main() {
>>> auto x = 1;
>>> Tuple!(int,short) a;
>>> a[0] = 1;
>>> a[x] = 2;
>>> }
>>>
>>> If I use a value instead of a variable ie. a[1] = 2; it compiles fine.
>>
>> The index need to be a compile-time constant, you cannot index a tuple
>> with a runtime value.
>> Try using
>>
>> enum x = 1;
>>
>>
>> Philippe
>
> Ah I didn't know this, thanks. That makes a tuple pretty useless for
> what I
> was doing now as I was reading the "index" in from a file. Guess I'll
> find
> another way round it.
You still can do it, but you have to do it by still using compile-time
constants as indexes:
auto x = 1;
Tuple!(int, short) a;
a[0] = 1;
switch(x)
{
case 0:
a[0] = 2;
break;
case 1:
a[1] = 2;
break;
default:
assert(0, "does not compute!");
}
the point is, the compiler has no idea what the lvalue expression's type
should be when you do:
a[x] = 1;
is it short or int?
so the compiler must *know* what type x is at compile time in order for
this to be valid.
-Steve
More information about the Digitalmars-d-learn
mailing list