Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
591 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...