How would you do this in D?

Jose Armando Garcia jsancio at gmail.com
Tue May 10 18:06:27 PDT 2011


Thanks. I should have read
http://www.digitalmars.com/d/2.0/template.html more carefully.

"Multiple instantiations of a TemplateDeclaration with the same
TemplateArgumentList, before implicit conversions, all will refer to
the same instantiation."

The default values which are evaluated at the call site are part of
the TemplateArgumentList.

On Tue, May 10, 2011 at 9:52 PM, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> wrote:
> On 5/10/11 7:32 PM, Jose Armando Garcia wrote:
>>
>> Hey guys,
>>
>> I am trying to create a function that return true or executes
>> "something" the n-th time it is called from a specific call site. How
>> would you do that in D? In C we can do that with the help of
>> pre-processor macros. E.g.:
>>
>> ---
>> #include<assert.h>
>>
>> #define EVERY(N, ACTION) { static int counter = 0; if(++counter>  (N))
>> counter -= (N); if(counter == 1) (ACTION); }
>>
>> int main()
>> {
>>    int i = 0;
>>    int j = 0;
>>    while(i<  10)
>>    {
>>       EVERY(10, ++j);
>>       EVERY(2, ++i);
>>    }
>>    assert(j == 2);
>>    assert(i == 10);
>> }
>> ---
>>
>> In D, I hacked the following implementation. I don't like this
>> implementation for a log of reason... Am I missing some D feature? Can
>> someone do better?
>
> [snip]
>
> Just use a static variable inside a function parameterized by __FILE__ and
> __LINE__. Indeed the drawback is that two every() calls in one line will
> share that static. I consider it a small matter. If it becomes a bear we may
> as well add __COLUMN__ or something similar.
>
> Note that the macro version has other, arguably larger, drawbacks - e.g. it
> can't be used as an expression, evaluates the limit multiple times. pollutes
> the global namespace etc.
>
>
> Andrei
>
>


More information about the Digitalmars-d mailing list