简体   繁体   中英

multi-dimensional array based on std::array

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM