Foreach/opApply with @nogc

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 24 12:36:18 PDT 2014


On Sun, 24 Aug 2014 19:23:01 +0000
Stefan Frijters via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:

> request I do have a followup question: is it possible somehow to 
> have both a @nogc and a normal opApply function available?
you can use templated opApply():

  import std.traits;


  struct NumberRange {
     int begin;
     int end;

     int opApply(Dg) (scope Dg dg) if (ParameterTypeTuple!Dg.length == 1) {
       int result = 0;

       for (int number = begin; number != end; ++number) {
         result = dg(number);

         if (result) {
           break;
         }
       }
       return result;
     }
  }


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

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


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


this works, but you must use 
  foreach (int n; NumberRange(3, 7)) { ... }
instead of
  foreach (n; NumberRange(3, 7)) { ... }

'cause compiler can't infer types in the last case.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20140824/9ecb6b32/attachment.sig>


More information about the Digitalmars-d-learn mailing list