Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegantly define multi-dimensional array in modern C++

Defining multi-dimensional array using the T[][][] syntax is easy. However, this creates a raw array type which doesn't fit nicely into modern C++. That's why we have std::array since C++11. But the syntax to define a multi-dimensional array using std::array is quite messy. For example, to define a three-dimensional int array, you would have to write std::array<std::array<std::array<int, 5>, 5>, 5>. The syntax doesn't scale at all. I'm asking for a fix for this issue. Maybe, this issue cannot be fixed using existing utility provided by C++. In that case, I'm happy with a custom tool developed to ease the syntax.

Found a solution myself:

template <typename T, std::size_t n, std::size_t... ns>
struct multi_array {
  using type = std::array<typename multi_array<T, ns...>::type, n>;
};

template <typename T, std::size_t n>
struct multi_array<T, n> {
  using type = std::array<T, n>;
};

template <typename T, std::size_t... ns>
using multi_array_t = typename multi_array<T, ns...>::type;

Wondering whether the implementation can be further simplified.

like image 726
Lingxi Avatar asked Jan 26 '16 06:01

Lingxi


1 Answers

Refer to Multi-dimensional arrays in C++11

template <class T, std::size_t I, std::size_t... J>
struct MultiDimArray 
{
  using Nested = typename MultiDimArray<T, J...>::type;
  // typedef typename MultiDimArray<T, J...>::type Nested;
  using type = std::array<Nested, I>;
  // typedef std::array<Nested, I> type;
};

template <class T, std::size_t I>
struct MultiDimArray<T, I> 
{
  using type = std::array<T, I>;
  // typedef std::array<T, I> type;
};

MultiDimArray<float, 3, 4, 5, 6, 7>::type floats;

MultiDimArray is a pair of meta-functions to compute nested type for multi-dimensional std::array. The most general MultiDimArray is a variadic template of unsigned integers to pass an arbitrary number of dimensions. The terminating MultiDimArray specialization defines the simplest case of single dimensional std::array.

like image 180
zangw Avatar answered Nov 13 '22 00:11

zangw