展开的静态数组循环

时间:2014-02-06 22:49:29

标签: static d loop-unrolling static-array iota

如果我调用该函数

/** 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;
    }
}
带有静态数组的

将在发布模式下自动为我展开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; }
}

用于实现展开而不是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;
    }
}

看起来不错吗?

1 个答案:

答案 0 :(得分:5)

  带有静态数组的

会自动为我展开foreach吗?

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

  

如果没有,我可以使用静态iota(siota)来实现这个目标吗?

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

  

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

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