foreach, tupleof

Philippe Sigaud philippe.sigaud at
Mon Mar 8 12:54:42 PST 2010

On Sun, Mar 7, 2010 at 19:53, Ellery Newcomer <ellery-newcomer at>wrote:

> On 03/07/2010 12:23 PM, Jacob Carlborg wrote:
>> It's a bug:
>> You can use the following code as a workaround:
>> foreach (i, dummy ; s.tupleof)
>> s.tupleof[i] = 1;
> Totally awesome! Thanks a float.infinity!

I remember spending *weeks* (well, OK, *hours*) trying to find a way to do
such a mapping after trying the first foreach, and getting some recursive
template to work... Only to find this static foreach trick, looking at
Phobos code (for D2) some month after. It sent ripples in all my code...

As a side note, it works for any tuple: those created by .tupleof, but also
the variadic template parameters, the expansion of a std.typecons.Tuple
(D2), those created by templates, etc. So you can do:

void reinitialize(T...)(ref T ts) // Variadic template
    foreach(i, Type; T) ts[i] = T[i].init; // iterating on the components of

int a = 1;
char c = 'a';
string s = "abc";


assert(a = 0); // int.init
assert(c =  char.init); // is there a literal for char.init? '' doesn't

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Digitalmars-d-learn mailing list