Variadic模板多维数组容器

Ric*_*y65 12 c++ multidimensional-array variadic-templates c++11

在C++ 0x Variadic Templates Proposal paper Link中,有一个类的例子,它支持任意数量的维度.我在下面复制了它:

template<typename T, unsigned PrimaryDimension, unsigned... Dimensions>
class array { /* implementation */ };

array<double, 3, 3> rotation matrix; // 3x3 rotation matrix
Run Code Online (Sandbox Code Playgroud)

遗憾的是没有提供实施.由于我对可变参数模板相对较新,我有兴趣看到这个容器的实现.

感谢任何能提供简单实施的人.

Fai*_*ali 23

这是一个非常简单的实现(使用gcc4.6.1编译),它演示了正确获取数组类型所涉及的递归 - 如果您有其他一些您感兴趣的具体实现细节,请告诉我们:

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;
}
Run Code Online (Sandbox Code Playgroud)