gpt4 book ai didi

c++ - 如何在编译时生成嵌套循环

转载 作者:IT老高 更新时间:2023-10-28 12:47:59 25 4
gpt4 key购买 nike

我有一个整数N,我在编译时就知道了。我还有一个 std::array 保存描述 N 维数组形状的整数。我想在编译时使用元编程技术生成嵌套循环,如下所述。

constexpr int N {4};
constexpr std::array<int, N> shape {{1,3,5,2}};


auto f = [/* accept object which uses coords */] (auto... coords) {
// do sth with coords
};

// This is what I want to generate.
for(int i = 0; i < shape[0]; i++) {
for(int j = 0; j < shape[1]; j++) {
for(int k = 0; k < shape[2]; k++) {
for(int l = 0; l < shape[3]; l++) {
f(i,j,k,l) // object is modified via the lambda function.
}
}
}
}

注意参数 N 在编译时是已知的,但在编译之间可能会发生不可预测的变化,因此我不能像上面那样对循环进行硬编码。理想情况下,循环生成机制将提供一个接口(interface),该接口(interface)接受 lambda 函数,生成循环并调用生成上述等效代码的函数。我知道可以在运行时用一个 while 循环和一组索引编写一个等效循环,并且已经有了这个问题的答案。但是,我对这个解决方案不感兴趣。我也对涉及预处理器魔法的解决方案不感兴趣。

最佳答案

类似这样的东西(注意:我将“形状”作为可变参数模板参数集..)

#include <iostream>

template <int I, int ...N>
struct Looper{
template <typename F, typename ...X>
constexpr void operator()(F& f, X... x) {
for (int i = 0; i < I; ++i) {
Looper<N...>()(f, x..., i);
}
}
};

template <int I>
struct Looper<I>{
template <typename F, typename ...X>
constexpr void operator()(F& f, X... x) {
for (int i = 0; i < I; ++i) {
f(x..., i);
}
}
};

int main()
{
int v = 0;
auto f = [&](int i, int j, int k, int l) {
v += i + j + k + l;
};

Looper<1, 3, 5, 2>()(f);

auto g = [&](int i) {
v += i;
};

Looper<5>()(g);

std::cout << v << std::endl;
}

关于c++ - 如何在编译时生成嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393694/

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