Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];

?

like image 739
iBug Avatar asked Feb 04 '26 06:02

iBug


1 Answers

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

like image 90
Brian Bi Avatar answered Feb 05 '26 20:02

Brian Bi