2

I need a template that gives a multi-dimensional array based on std::array.

template <typename T, size_t...>
using MyArray = ? // -> here is something I don't know how to write...

The usage is as follows:

static_assert(std::is_same_v<
  MyArray<int, 2>, std::array<int, 2>
>);

static_assert(std::is_same_v<
  MyArray<int, 2, 3>, std::array<std::array<int, 3>, 2>
>);  // the dimension should be the opposite order

MyArray a;    // a stacked 2-D array of size 2x3
a[0][2] = 2;  // valid index

Any help will be appreciated!

max66
  • 65,235
  • 10
  • 71
  • 111
Jes
  • 2,614
  • 4
  • 25
  • 45
  • 1
    Do you really need a multi-dimensional array? You can often use a *m* * *n* sized array instead of *m* instances of an *n*-sized array. Then you can emulate the two-dimensional behaviour with simple accessor and mutator functions. – tadman Aug 09 '18 at 17:40
  • I think this one is a duplicate of https://stackoverflow.com/questions/17759757/multidimensional-stdarray – goutnet Aug 09 '18 at 17:49

1 Answers1

4

I don't know how to make it with only a using; the best I can imagine needs the helps of an helper struct.

Something as follows

template <typename, std::size_t ...>
struct MyArrayHelper;

template <typename T, std::size_t D0, std::size_t ... Ds>
struct MyArrayHelper<T, D0, Ds...>
 { using type = std::array<typename MyArrayHelper<T, Ds...>::type, D0>; };

template <typename T>
struct MyArrayHelper<T>
 { using type = T; };

template <typename T, std::size_t ... Ds>
using MyArray = typename MyArrayHelper<T, Ds...>::type;
max66
  • 65,235
  • 10
  • 71
  • 111