Arbitrary Dimensional Array Using Variadic Templates
How to create an Array class in C ++ 11 that can be used like
Array < int, 2, 3, 4> a, b;
Array < char, 3, 4> d;
Array < short, 2> e;
and access it in a way like
a[2][1][2] = 15;
d[1][2] ='a';
I also need to overload the operator like
T &operator[size_t i_1][size_t i_2]...[size_t i_D];
which doesn't exist. How can i do this?
source to share
The easiest way to do this is to nest std::array
:
#include<array>
template<class T, size_t size, size_t... sizes>
struct ArrayImpl {
using type = std::array<typename ArrayImpl<T, sizes...>::type, size>;
};
template<class T, size_t size>
struct ArrayImpl<T, size> {
using type = std::array<T, size>;
};
template<class T, size_t... sizes>
using Array = typename ArrayImpl<T, sizes...>::type;
In this solution, it is the Array<char, 3, 4>
same as an array std::array<std::array<char, 4>, 3>
- consisting of arrays of lower dimension.
It also shows how you can implement operator[]
for many dimensions. operator[]
your object should return an object for which it is also defined operator[]
. In this case, it is a reference to a smaller array.
source to share
Try the following:
#include <iostream>
template <typename T, int N1, int... N2>
class Array
{
public:
Array() {}
~Array() {}
Array<T,N2...>& operator[](int index)
{
return data[index];
}
private:
Array<T,N2...> data[N1];
};
template<typename T, int N>
class Array<T,N>
{
public:
Array() {}
~Array() {}
T& operator[](int index)
{
return data[index];
}
private:
T data[N];
};
int main()
{
Array < int, 2, 3, 4> a, b;
Array < char, 3, 4> d;
Array < short, 2> e;
a[0][1][2] = 15;
d[1][2] = 'a';
std::cout << "a[0][1][2] = " << a[0][1][2] << std::endl;
std::cout << "d[1][2] = " << d[1][2] << std::endl;
return 0;
}
You may also need to do a range check and maybe some iterators will look :)
source to share