How to linearize N-dimensional array index?

I'm trying to implement a simple n-dimensional array / tensor. Right now my class definition looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstddef>
#include <array>

 
template <typename T, size_t rank>
class Tensor {
public:
    Tensor() = default;
    explicit Tensor(const std::array<unsigned, rank>& shape);
    ~Tensor();

    T& operator()(const std::array<unsigned, rank>& shape);
    T operator()(const std::array<unsigned, rank>& shape) const;
    
    template<typename... Indices>
    T& operator()(Indices... indices); // turns indices to array and calls the other overload

    template<typename... Indices>
    T operator()(Indices... indices) const;
private:
    T* data;
    std::array<unsigned, rank> shape;
    size_t _size;
};


I'm using the () operator to set and retrieve items. I would like to know how to transform the array of indices to a 1D index.
x -> data[x]
x,y -> data[x*columns+y]
x,y,z -> data[x*columns*height + y*height + z]
{x_1, ..., x_n} -> data[ x_1 \Prod_2^n size_j + x_2 \Prod_3^n size_j + ... + x_n ]
Topic archived. No new replies allowed.