使用Variadic模板的任意维数组 [英] Arbitrary dimensional array using Variadic templates
问题描述
如何在C ++ 11中创建一个Array类,可以像
一样使用 Array< int,2,3,4> a,b;
Array< char,3,4> d;
Array<短,2> e;
并以
<$> p $ p>
a [2] [1] [2] = 15;
d [1] [2] ='a';
我还需要重载operator
T& operator [size_t i_1] [size_t i_2] ... [size_t i_D];
不存在。
最简单的方法是通过嵌套 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;
在此解决方案中 Array< char,3,4>
与 std :: array< std :: array< char,4>,3>
相同。
这也显示了如何为多个维度实现 operator []
。 运算符[]
需要返回为其定义 operator []
的对象。在这种情况下,它引用一个较小维数的数组。
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?
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.
这篇关于使用Variadic模板的任意维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!