Static 静态数组的展开循环
如果我调用函数Static 静态数组的展开循环,static,d,loop-unrolling,static-array,iota,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)
/** 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;
}
}
看起来还好吗
使用静态数组,D会自动为我展开foreach吗
不,语言不能保证这一点。某些实现(编译器)可能会作为优化展开循环
如果没有,我的静态物联网(siota)实现能否实现这一点
是的,在元组上使用foreach会为每次“迭代”生成代码,从而有效地展开循环
此外,DMD是否有一个生成汇编代码的标志,以便我自己将来可以研究DMD生成的代码
否,DMD无法发出程序集列表。您可以使用反汇编程序(如or)或其他编译器。David Simcha在DConf 2013上给出了一个示例,其中包括一节关于使用D的元编程功能进行自动循环展开的内容。如果我没有弄错的话,所有D编译器都会展开。甚至DMD。但正如你所说,这不是保证。