Variadic模板多维数组容器 [英] Variadic Templates Multidimensional Array Container
问题描述
在C ++ 0x Variadic模板建议书链接 a>有一个支持任意维数的类的例子。我复制了它:
In the C++0x Variadic Templates Proposal paper Link there is an example of a class which supports an arbitrary number of dimensions. I have copied it below:
template<typename T, unsigned PrimaryDimension, unsigned... Dimensions>
class array { /* implementation */ };
array<double, 3, 3> rotation matrix; // 3x3 rotation matrix
很遗憾,没有提供实现。由于我是相对较新的可变参数模板,我有兴趣看到这个容器的实现。
Sadly the implementation is not provided. As I am relatively new to variadic templates I would be interested to see an implementation of this container.
感谢任何可以提供简单实现的人。
Thanks to anybody who can provide a simple implementation.
推荐答案
下面是一个非常简单的实现(使用gcc4.6.1编译),演示了在获取数组类型时所涉及的递归 - 如果您有其他具体的实现细节,请告诉我们:
Here is a very simple implementation (compiled with gcc4.6.1) that demonstrates the recursion involved in getting the array type right - if there is some other specific implementation detail you are interested in, please let us know:
template<class T, unsigned ... RestD> struct array;
template<class T, unsigned PrimaryD >
struct array<T, PrimaryD>
{
typedef T type[PrimaryD];
type data;
T& operator[](unsigned i) { return data[i]; }
};
template<class T, unsigned PrimaryD, unsigned ... RestD >
struct array<T, PrimaryD, RestD...>
{
typedef typename array<T, RestD...>::type OneDimensionDownArrayT;
typedef OneDimensionDownArrayT type[PrimaryD];
type data;
OneDimensionDownArrayT& operator[](unsigned i) { return data[i]; }
};
int main()
{
array<int, 2, 3>::type a4 = { { 1, 2, 3}, { 1, 2, 3} };
array<int, 2, 3> a5{ { { 1, 2, 3}, { 4, 5, 6} } };
std::cout << a5[1][2] << std::endl;
array<int, 3> a6{ {1, 2, 3} };
std::cout << a6[1] << std::endl;
array<int, 1, 2, 3> a7{ { { { 1, 2, 3}, { 4, 5, 6 } } }};
std::cout << a7[0][1][2] << std::endl;
}
这篇关于Variadic模板多维数组容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!