c++ - 可变参数模板多维数组容器

标签 c++ c++11 multidimensional-array variadic-templates

在 C++0x 可变参数模板提案论文中 Link有一个支持任意维数的类的示例。我已将其复制如下:

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

array<double, 3, 3> rotation matrix; // 3x3 rotation matrix

遗憾的是没有提供实现。由于我对可变参数模板比较陌生,所以我很想看看这个容器的实现。

感谢任何可以提供简单实现的人。

最佳答案

这是一个非常简单的实现(使用 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;
}

关于c++ - 可变参数模板多维数组容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058098/

相关文章:

使用 IShellDispatch 的 C++ 解压缩失败

c++ - 为什么我对 operator* 的使用失败了?

c++ - 为什么在 C++ 中使用多线程时运行时间没有减半?

c++ - 隐式使用析构函数

c++ - if(cin) 的目的?

c - 将数组传递给 C 中的函数

c++ - 输出指针的 const 前缀

c# - 从非托管 C 库访问 C# 方法是否安全?

arrays - 在 matlab 中,我应该使用什么来收集不同对象的集合?

C++ 二维数组查询