展开的静态数组循环

Nor*_*löw 2 static d static-array iota loop-unrolling

如果我调用该函数

/** Check if all Elements, possibly recursively, of $(D x) are zero. */
bool allZero(T)(in T x) @safe pure nothrow {
    import std.range: isIterable;
    static if (isIterable!T) {
        foreach (ref elt; x) {
            if (!elt.allZero) { return false; }
        }
        return true;
    } else {
        return x == 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用静态数组,D会foreach在发布模式下自动为我展开吗?

如果不能

/** Static Iota. */
import std.typetuple: TypeTuple;
template siota(size_t from, size_t to) { alias siotaImpl!(to-1, from) siota; }
private template siotaImpl(size_t to, size_t now) {
    static if (now >= to) { alias TypeTuple!(now) siotaImpl; }
    else                  { alias TypeTuple!(now, siotaImpl!(to, now+1)) siotaImpl; }
}
Run Code Online (Sandbox Code Playgroud)

用来实现展开而不是foreach

还有一个DMD的标志,它生成汇编代码,以便我将来可以调查DMD生成的代码吗?

更新:到目前为止,这是我的解决方案.

/** Check if all Elements, possibly recursively, of $(D x) are zero. */
bool allZero(T, bool useStatic = true)(in T x) @safe pure nothrow { // TODO: Extend to support struct's and classes's'
    static        if (useStatic && isStaticArray!T) {
        foreach (ix; siota!(0, x.length)) {
            if (!x[ix].allZero) { return false; } // make use of siota?
        }
        return true;
    } else static if (isIterable!T) {
        foreach (ref elt; x) {
            if (!elt.allZero) { return false; }
        }
        return true;
    } else {
        return x == 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

它看起来不错吗?

Vla*_*eev 5

有了静态数组,D会自动为我展开foreach吗?

不,语言不保证.某些实现(编译器)可能会将循环展开为优化.

如果没有,我的静态iota(siota)的实现可以用于实现这一目标吗?

是的,在元组上使用foreach会为每次"迭代"生成代码,从而有效地展开循环.

还有一个DMD的标志,它生成汇编代码,以便我将来可以调查DMD生成的代码吗?

不,DMD无法发出汇编列表.您可以使用反汇编程序(例如obj2asmIDA)或其他编译器.