iBug
iBug

Reputation: 37317

C++ template using multidimensional arrays

Is it possible in C++ to write this:

template <typename T, size_t dim, size_t len>
using A = /* something */;

that will make these two lines equivalent:

/* 1 */ A<int, 3, 5> a;   A<char, 5, 3> c;

/* 2 */ int a[5][5][5];   char c[3][3][3][3][3];

?

Upvotes: 3

Views: 92

Answers (1)

Brian Bi
Brian Bi

Reputation: 119562

Is it possible? Yes, you can do arbitrarily complex calculations at compile-time, so there certainly is a solution.

The most straightforward way is to just use template recursion, like so:

template <class T, size_t dim, size_t len>
struct A_helper {
    using type = typename A_helper<T, dim - 1, len>::type[len];
};

template <class T, size_t len>
struct A_helper<T, 0, len> {
    using type = T;
};

template <class T, size_t dim, size_t len>
using A = typename A_helper<T, dim, len>::type;

See it on Coliru: http://coliru.stacked-crooked.com/a/bfc9052b30bce553

Upvotes: 5

Related Questions