gpt4 book ai didi

static - 静态数组的展开循环

转载 作者:行者123 更新时间:2023-12-02 04:37:38 24 4
gpt4 key购买 nike

如果我调用函数

/** 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?

不,DMD 不能发布程序集列表。您可以使用反汇编器(例如 obj2asmIDA ),或使用不同的编译器。

关于static - 静态数组的展开循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com