Arbitrary dimensional array using Variadic templates

左心房为你撑大大i 提交于 2019-11-30 09:20:57

问题


How can I create an Array class in C++11 which 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 operator as

T &operator[size_t i_1][size_t i_2]...[size_t i_D]; 

which does not exist. How can I do this?


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/30155608/arbitrary-dimensional-array-using-variadic-templates

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