How to foreach over a DList?

Ali Çehreli acehreli at yahoo.com
Mon Mar 31 14:49:01 PDT 2014


On 03/31/2014 10:50 AM, Jeroen Bollen wrote:
> I am trying to foreach over a std.container.DList but it isn't working.
> I have tried the following code:
> https://gist.github.com/Binero/f30e56351baf05f1a2ec
>
> I am getting the following errors:
>
> /usr/include/dlang/dmd/std/container.d(1925): Error: template
> std.container.DList!ubyte.DList.insertBeforeNode cannot deduce function
> from argument types !()(typeof(null), int), candidates are:
> /usr/include/dlang/dmd/std/container.d(2096):
> std.container.DList!ubyte.DList.insertBeforeNode(Stuff)(Node* n, Stuff
> stuff) if (isInputRange!Stuff &&
> isImplicitlyConvertible!(ElementType!Stuff, T))
> /usr/include/dlang/dmd/std/container.d(2155):
> std.container.DList!ubyte.DList.insertBeforeNode(Stuff)(Node* n, Stuff
> stuff) if (isImplicitlyConvertible!(Stuff, T))
> source/app.d(7): Error: template instance
> std.container.DList!ubyte.DList.insertBack!int error instantiating
> source/app.d(11): Error: invalid foreach aggregate list1

Some notes:

1) DList is a struct. So, there is no need for 'new'. However, new is 
not an error but then the ~= syntax below cannot work on list1 without 
dereferencing. (You did not use ~=, I just liked it. :) )

     (*list1) ~= cast(ubyte)3;    // would work

2) For the same reason, list1[] becomes plain array slicing and the 
compiler is looking for "upper and lower bound to slice pointer". This 
would work:

     (*list1)[]

3) 1, 2, and 3 are ints. So, I had to cast them.

import std.container;
import std.stdio;

void main()
{
     auto list1 = DList!ubyte();

     list1.insertBack(cast(ubyte)1);
     list1.insertBack(cast(ubyte)2);
     list1 ~= cast(ubyte)3;    // alternative syntax

     foreach(ubyte item; list1[]) {
         writeln(item);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list