How to generate nested loops at compile time

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

    Assuming you don't want total loop unrolling, just generation of i, j, k etc. argument tuples for f:

    #include 
    #include       // std::integer_sequence
    
    template< int dim >
    constexpr auto item_size_at()
        -> int
    { return ::shape[dim + 1]*item_size_at(); }
    
    template<> constexpr auto item_size_at<::N-1>() -> int { return 1; }
    
    template< size_t... dim >
    void call_f( int i, std::index_sequence )
    {
        f( (i/item_size_at() % ::shape[dim])... );
    }
    
    auto main()
        -> int
    {
        int const n_items = ::shape[0]*item_size_at<0>();
        for( int i = 0; i < n_items; ++i )
        {
            call_f( i, std::make_index_sequence<::N>() );
        }
    }
    

提交回复
热议问题