Arbitrary dimensional array using Variadic templates

随声附和 提交于 2019-11-29 14:58:15

The simplest way to do this is by nesting 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 Array<char, 3, 4> is the same as std::array<std::array<char, 4>, 3> - array consisting of arrays of smaller dimension.

This also shows how you can implement operator[] for many dimensions. operator[] of your object needs to return object for which operator[] is also defined. In this case it is reference to an array of smaller dimension.

Try this:

#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 might also want to throw in range checking and perhaps some iterators to be fancy :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!