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

Imperatorn johan_forsberg_86 at hotmail.com
Tue Oct 25 09:51:58 UTC 2022


On Monday, 24 October 2022 at 21:52:18 UTC, Ali Çehreli wrote:
> On 10/24/22 14:26, Per Nordlöw wrote:
>> [...]
>
> 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

I didn't know about that esoteric feature. like this approach


More information about the Digitalmars-d-learn mailing list