foreach, tupleof

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


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

> On 03/07/2010 12:23 PM, Jacob Carlborg wrote:
>
>> It's a bug: http://d.puremagic.com/issues/show_bug.cgi?id=2411
>> 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
T.
}

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

reinitialize(a,c,s);

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


Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100308/8f27b35b/attachment.htm>


More information about the Digitalmars-d-learn mailing list