How to generate nested loops at compile time

后端 未结 4 1228
逝去的感伤
逝去的感伤 2021-02-01 03:34

I have an integer N which I know at compile time. I also have an std::array holding integers describing the shape of an N-dime

4条回答
  •  借酒劲吻你
    2021-02-01 04:18

    I suppose this is exactly what you asked for:

    #include 
    #include 
    
    constexpr int N{4};
    constexpr std::array shape {{1,3,5,2}};
    
    // Diagnositcs
    
    template
    struct TPrintf {
            constexpr static void call(V v, Vals ...vals) {
                    std::cout << v << " ";
                    TPrintf::call(vals...);
            }
    };
    
    template
    struct TPrintf {
            constexpr static void call(V v) {
                    std::cout << v << std::endl;
            }
    };
    
    
    template
    constexpr void t_printf(Vals ...vals) {
            TPrintf::call(vals...);
    }
    
    // Unroll
    
    template
    struct NestedLoops {
            template
            constexpr static void call(const F& f, RtIdx ...idx) {
                    for(int i = 0; i < shape[CtIdx]; ++i) {
                            NestedLoops::call(f, idx..., i);
                    }
            }
    };
    
    template
    struct NestedLoops {
            template
            constexpr static void call(const F& f, RtIdx ...idx) {
                    for(int i = 0; i < shape[N-1]; ++i) {
                            f(idx..., i);
                    }
            }
    };
    
    template
    void nested_loops(const F& f) {
            NestedLoops<0, F>::call(f);
    }
    
    int main()
    {
            auto lf = [](int i, int j, int k, int l) {
                    t_printf(i,j,k,l);
            };
    
            nested_loops(lf);
            return 0;
    }
    

提交回复
热议问题