Search code examples
foreachoperator-overloadingd

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]) {}

Solution

  • 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.