编译时的坐标生成

Coordinate generation at compile time

本文关键字:坐标 编译      更新时间:2023-10-16

给定在编译时指定N维框形状的hana::tuple(例如3D中的(2,3,2)),我希望在编译时生成具有所有坐标组合的元组。 (0,0,0) (0,0,1) (0,1,0) (0,1,1) (0,2,0) (0,2,1) (1,0,0) (1,0,1) (1,1,0) (1,1,1) (1,2,0) (1,2,1)

这个问题与我几天前发布的另一个问题有关(链接),但为hana重新制定。我似乎很难想出一个尊重hana::tuple对象不变性的算法。我无法识别hana算法的组合将允许我生成递归调用,同时收集返回的元组。

根据您的评论,您只是在尝试执行循环展开。您可能想同时测量这两种方法,但通常情况下,当数组边界已知时,编译器在优化这些方面会比您做得更好。实际上,通过强制循环展开,您可能会显著降低程序速度或使程序膨胀。

话虽如此,如果这是你想做的,下面是你可以做的:

#include <boost/hana.hpp>
namespace hana = boost::hana;
template <int ...> struct your_template { };
int main() {
    auto xs = hana::to_tuple(hana::range_c<int, 0, 10>); // [0, ..., 9]
    auto ys = hana::to_tuple(hana::range_c<int, 0, 10>); // [0, ..., 9]
    auto zs = hana::to_tuple(hana::range_c<int, 0, 10>); // [0, ..., 9]
    auto coords = hana::cartesian_product(hana::make_tuple(xs, ys, zs));
    hana::for_each(coords, hana::fuse([](auto x, auto y, auto z) {
        your_template<decltype(x)::value, decltype(y)::value, decltype(z)::value> foo;
        (void)foo;
    }));
}

但是,请注意,在编译时生成笛卡尔乘积是非常麻烦的,因为您正在生成一个巨大的元组。例如,上面的内容在我的盒子上编译大约需要10秒。