How to generate nested loops at compile time

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

    Another variant of the same thing:

    template 
    struct Looper
    {
        template 
        void operator()(const std::array& shape, Functor functor)
        {
            for (int index = 0; index < shape[shape_index]; ++index)
            {
                Looper()
                    (
                        shape,
                        [index, &functor](auto... tail){ functor(index, tail...); }
                    );
            }
        }
    };
    
    template 
    struct Looper
    {
        template 
        void operator()(const std::array&, Functor functor)
        {
            functor();
        }
    };
    
    template 
    void loop(const std::array& shape, Functor functor)
    {
        Looper<0, shape_size>()(shape, functor);
    }
    

    Example of use:

    constexpr size_t N {4};
    
    constexpr std::array shape {{1,3,5,2}};
    
    void f(int i, int j, int k, int l)
    {
        std::cout
            << std::setw(5) << i
            << std::setw(5) << j
            << std::setw(5) << k
            << std::setw(5) << l
            << std::endl;
    }
    
    // ...
    
    loop(shape, f);
    

    Live demo

提交回复
热议问题