编程语言中的foreach语句重载

Ale*_*ann 7 foreach d

您好我想定义自己的类集合,并在foreach语句中使其可迭代,如下所示:

public class Collection(Type)
{
    ...
    private T head;
    private Collection!(T) queue;
}

Collection!(int) temp;
foreach (int t; temp) { ... }
Run Code Online (Sandbox Code Playgroud)

我应该定义什么方法,以及如何定义?

rat*_*eak 9

您可以指定front,popfront()empty功能:(但除非你用保存此会消耗您的收藏())

public class Collection(T) { ... private T head;  private Collection!(T) queue;

    @property T front(){
        return head;
    }

    @property bool empty(){
        return queue is null;
    }

    void popfront(){
        head = queue.head;
        queue = queue.queue;
    }

    Collection!T save(){
        return new Collection!T(head,queue);
    }

}
Run Code Online (Sandbox Code Playgroud)

或使用专用结构进行迭代(如std.container模块中所做的那样)

public class Collection(T) { ... private T head;  private Collection!(T) queue;

    Range opSlice(){
        return Range(head,queue);
    }

    struct Range{
        T h;
        Collection!(T) q;
        this(T he, Collection!(T) qu){
            h=he;
            q=qu;
        }
        @property T front(){
            return h;
        }

        @property bool empty(){
            return q is null;
        }

        void popfront(){
            h = q.head;
            q= q.queue;
        }

        Collection!T save(){
            return this;
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

所以迭代就这样完成了

Collection!(int) temp; foreach (int t;temp[]) { ... }
Run Code Online (Sandbox Code Playgroud)

你也可以添加一个opApply正常的foreach:

public int opApply(int delegate(ref T) dg){
    int res=0;
    foreach(ref T;this[]){
        res = dg(t);
        if(res)return res;
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用专用结构.范围与容器的不同之处在于迭代时消耗它,当迭代容器时您不想使用它.阵列是一种混合...... (3认同)

Vla*_*lad 5

看一下ForeachStatements上的这个文档并向下滚动一下.

如果我正确地阅读您的示例,您可以按如下方式定义opApplyfor Collection:

public int opApply(int delegate(ref T) dg){

    Collection!T p = this;

    int res = 0;
    while(!res && p !is null){
        res = dg(p.head);
        p = p.queue;
    }

    return res;
}
Run Code Online (Sandbox Code Playgroud)