How to generate nested loops at compile time

后端 未结 4 1242
逝去的感伤
逝去的感伤 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:07

    Something like this (NOTE: I take the "shape" as a variadic template argument set..)

    #include 
    
    template 
    struct Looper{
        template 
        constexpr void operator()(F& f, X... x) {
            for (int i = 0; i < I; ++i) {
                Looper()(f, x..., i);
            }
        }
    };
    
    template 
    struct Looper{
        template 
        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;
    }
    

提交回复
热议问题