Foreach/opApply with @nogc

Stefan Frijters via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 24 12:23:01 PDT 2014


On Sunday, 24 August 2014 at 18:55:09 UTC, ketmar via 
Digitalmars-d-learn wrote:
> On Sun, 24 Aug 2014 11:45:14 -0700
> Ali Çehreli via Digitalmars-d-learn 
> <digitalmars-d-learn at puremagic.com>
> wrote:
>
>> Yeah, the only reason why the original code does not work is 
>> the
>> write() expression in the foreach body.
> hm. really. i forgot what is delegate body for opApply. sure, 
> here we
> can't use @nogc delegate. my fault.

Apologies for the misunderstanding. Before I close my enhancement 
request I do have a followup question: is it possible somehow to 
have both a @nogc and a normal opApply function available? My 
code would like to have @nogc in as many places as possible, but 
there will be places where I cannot make the foreach body @nogc 
(I think; maybe some more Phobos functions can be annotated as 
well and the problem would go away).

So I basically want something like this:

void bar() @nogc { }
void foreachBar() @nogc {
   foreach (element; NumberRange(3, 7)) { bar(); }
}

void foo() { }
void foreachFoo() {
   foreach (element; NumberRange(3, 7)) { foo(); }
}

void main() {
   foreachBar();
   foreachFoo();
}

Obviously if I have one opApply function one of the two functions 
complains
opapply.d(36): Error: @nogc function 'opapply.foreachBar' cannot 
call non- at nogc function 'opapply.NumberRange.opApply'
or
opapply.d(44): Error: function opapply.NumberRange.opApply (int 
delegate(ref int) @nogc operations) const is not callable using 
argument types (int delegate(ref int __applyArg0) @system)

If I add a second opApply function (one with @nogc, the other 
without) the compiler cannot distinguish between the two:

opapply.d(36): Error: NumberRange(3, 7).opApply matches more than 
one declaration:
opapply.d(5):     const @nogc int(int delegate(ref int) @nogc 
operations)
and:
opapply.d(18):     const int(int delegate(ref int) operations)
opapply.d(36): Error: cannot uniquely infer foreach argument types
opapply.d(44): Error: NumberRange(3, 7).opApply matches more than 
one declaration:
opapply.d(5):     const @nogc int(int delegate(ref int) @nogc 
operations)
and:
opapply.d(18):     const int(int delegate(ref int) operations)
opapply.d(44): Error: cannot uniquely infer foreach argument types

Is this maybe something that could be used as an enhancement 
request? Or I guess what I want is basically an 'inout' kind of 
thing for @nogc...


More information about the Digitalmars-d-learn mailing list