Supporting foreach (k, v; T.init) for a user-defined (container) type

Ali Çehreli acehreli at yahoo.com
Mon Oct 24 21:52:18 UTC 2022


On 10/24/22 14:26, Per Nordlöw wrote:
> What property of a container (type) `T` enables iteration as
> 
> ```d
> foreach (k, v; T.init)
> {
>      ...
> }
> ```
> 
> ? I thought it sufficed to define `T.byKeyValue` but its presence seem 
> to have no effect.

Another option is to use range functions where front() returns a Tuple. 
We have an esoteric feature where a tuple expands automatically in 
foreach loops:

import std.typecons : tuple;
import std.conv : to;
import std.stdio : writeln;
import std.range : take;

struct S {
     size_t count;
     bool empty = false;

     auto front() {
         const key = count;
         const value = key.to!string;
         return tuple(key, value);    // <-- HERE
     }

     void popFront() {
         ++count;
     }
}

void main() {
     foreach (k, v; S.init.take(10))
     {
         writeln(k, ": ", v);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list