【问题标题】:C++ template using multidimensional arrays使用多维数组的 C++ 模板
【发布时间】:2017-11-18 07:40:08
【问题描述】:

在 C++ 中是否可以这样写:

template <typename T, size_t dim, size_t len>
using A = /* something */;

这将使这两行等效:

/* 1 */ A<int, 3, 5> a;   A<char, 5, 3> c;

/* 2 */ int a[5][5][5];   char c[3][3][3][3][3];

?

【问题讨论】:

  • 请详细说明“等效”。也许显示一些你想要工作的代码行以及你希望它们产生什么效果。

标签: c++ c++11 templates using


【解决方案1】:

有可能吗?是的,你可以在编译时进行任意复杂的计算,所以肯定有解决方案。

最直接的方法是只使用模板递归,如下所示:

template <class T, size_t dim, size_t len>
struct A_helper {
    using type = typename A_helper<T, dim - 1, len>::type[len];
};

template <class T, size_t len>
struct A_helper<T, 0, len> {
    using type = T;
};

template <class T, size_t dim, size_t len>
using A = typename A_helper<T, dim, len>::type;

在 Coliru 上查看:http://coliru.stacked-crooked.com/a/bfc9052b30bce553

【讨论】:

  • 我可以直接使用template&lt;typename T, size_t dim, size_t len&gt; using A = A&lt;T, dim-1, len&gt;[len]吗?
  • 即是否需要辅助类?
  • @iBug 您需要一些可以部分专门化的东西才能提供基本案例,而别名模板不能(部分或全部)专门化。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 2012-03-03
  • 1970-01-01
  • 2019-03-30
相关资源
最近更新 更多