简体   繁体   中英

How to add an 'opApply' on primitive types in D?

I've been trying to foreach through a character array in D but I can't figure out how to get it to work.

public MyClass opApply(MyClass delegate(int[]) dg) {
    // ...
    return myClass;
}

foreach(MyClass a; [5,6,9,2]) {}

You can't do what you want in the example precisely, but you can create a helper method/wrapper object to do almost the same thing.

So the result would be:

foreach(MyClass a; [5,6,9,2].byMyClass) {}

The byMyClass function would look something like this:

MyClassRange byMyClass(int[] array) {
      return MyClassRange(array);
}

MyClassRange is a helper object which provides the iteration:

struct MyClassRange {
      int[] array;
      this(int[] a) { array = a; }

      import std.array;

      bool empty() { return array.empty; }
      void popFront() { array.popFront; }
      MyClass front() { return new MyClass(array.front); }
}

Then, that thing can be used with foreach . For this exact example btw you could also just use foreach(MyClass c; [1,2,3].map!(a => new MyClass(a))) . The map function is found in std.algorithm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM