如果我调用该函数
/** 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;
}
}
使用静态数组,D 会在 Release模式下自动为我展开 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;
}
}
看起来还好吗?
最佳答案
with a static array will D unroll the foreach for me automatically?
不,该语言不能保证这一点。某些实现(编译器)可能会展开循环作为优化。
If not could my implementation of static iota (siota) be used to achieve this?
是的,在元组上使用 foreach 会为每次“迭代”生成代码,从而有效地展开循环。
Further is there a flag to DMD that generates assembly code so that I myself, in the future, can investigate the code generated by DMD?
关于static - 静态数组的展开循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615791/