On 03/17/2012 09:02 PM, Tongzhou Li wrote:
> On Saturday, 17 March 2012 at 23:05:30 UTC, Simen Kjærås wrote:
>> As for a workaround, have you considered using a simple array instead
>> of a linked list?
>> Arrays in D, especially when combined with std.array, make for
>> easy-to-use (though
>> perhaps not particularly efficient) stacks:
>>
>> int[] stack;
>>
>> stack ~= 3; // Push
>> stack = stack[0..$-1]; // Pop
>> stack.popBack(); // Pop with std.array
>
> Another problem. I wrote:
> Tuple!(double, char)[] stack;
> stack ~= tuple(10, '+');
> It won't compile:
> Error: cannot append type Tuple!(int,char) to type Tuple!(double,char)[]

Every template instantiation of a set of template parameters becomes a distinct type than any other set of template parameters.

In other words, Tuple!(double, char) and Tuple!(int, char) are distinct types. For all the compiler knows, Tuple is a user type and only the user should define whether they are compatible. Tuple does not define opCast() to covert from Tuple!(int,char) to Tuple!(double,char). I guess it could have been defined. (?)

A solution is to explicitly perform the conversion:

import std.conv;
// ...
    stack ~= to!(Tuple!(double, char))(tuple(10, '+'));

(An alias would make that easier to read. :/).

> I also tried:
> Tuple!(double, "Num", char, "Oper")[] stack;
> stack ~= tuple(10.0, '+');
> I also got an error:
> Error: cannot append type Tuple!(double,char) to type
> Tuple!(double,"Num",char,"Oper")[]

That's the same reason as above.

> But I tried:
> Tuple!(double, "Num", char, "Oper") t;
> t = tuple(10, 'a');
> It does compile.
> I don't understand why...

That's different because this time there is no slice involved. The assignment is done on t itself. Tuple defines opAssign() that effectively performs the following operations (calling the right-hand side object 'temp'):

t[0] = temp[0];
t[1] = temp[1];

And that succeeds because int can implicitly be converted to double.

Ali

Reply via email to