Search code examples
c++hpc

Variadic template tensor class


I'm trying to make a variadic template tensor class with as template parameters a type and a set of dimensions.

For example creating an array of 13 floats would use Tensor<float, 13> a; and creating a 3rd order 3 by 4 by 5 tensor of doubles would use Tensor<double, 3, 4, 5> b;. This is for a HPC application. Ultimately all elements need to append in memory, and the whole object should be allocated at once.

The object Tensor<double, 3, 4, 5> would have one field of type std::array<Tensor<double, 3, 4>, 5> maybe.

I'm having issues recursively defining this type with a variadic template. I'm currently trying the following code, but it doesn't compile, and have run out of ideas. I think adding a specialization template for sizeof(n) == 0 is a step in the right direction, but no luck.

#include <array>

template <typename T, int m, int ...n>
class Tensor {
public:
    std::array<Tensor<T, n>, m> a;
};

Alternatively a could just be a c-type array of whatever size is the product of the elements in n. How would I compute that product while still keeping the Tensor<double, 3, 4, 5> b; syntax for an uninitialized tensor?

Solution:

std::array<Tensor<T, n>, m> a; should be std::array<Tensor<T, n...>, m> a; and the class should be redefined so that e.g. Tensor<float, 3> is legal.


Solution

  • std::array<Tensor<T, n>, m> a; should be std::array<Tensor<T, n...>, m> a; and the class should be redefined so that e.g. Tensor<float, 3> is legal.