getNext
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Jul 13 08:03:46 PDT 2010
On 07/13/2010 05:09 AM, Shin Fujishiro wrote:
> Andrei Alexandrescu<SeeWebsiteForEmail at erdani.org> wrote:
>> I've just had an idea that is so dark and devious, I was almost afraid
>> to try it. But it works like a charm. Consider:
>>
>> T * getNext(R, E)(ref R range,
>> ref E store = *(cast(E*) alloca(E.sizeof))
>> {
>> ...
>> }
>>
>> With this, allocating a dummy buffer on caller's stack is automated, so
>> client code can just write:
>>
>> for (T * p; (p = getNext(r)); ) {
>> ... process *p ...
>> }
>>
>> I feel dirty.
>
> How about a TLS variable?
>
> template temporary(T)
> {
> static T temporary;
> }
> E* getNext(R, E)(ref R range, ref E store = temporary!E);
There's the classic problem of reusing the same temporary. Consider:
Range r1, r2;
ElementType!Range * p1, p2;
while ((p1 = getNext(r1)) && (p2 = getNext(r2)))
{
... oops ...
}
You need one temporary for each static occurrence of getNext.
Andrei
More information about the Digitalmars-d
mailing list