Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

c++ - Arbitrary dimensional array using Variadic templates

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...