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!

2
  • 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. Commented Aug 9, 2018 at 17:40
  • I think this one is a duplicate of stackoverflow.com/questions/17759757/multidimensional-stdarray Commented Aug 9, 2018 at 17:49

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.