我有一个模板类,其中包含以下规范:
template <typename T, size_t... Dims> class Array;
并说它可以如下使用:
// Define a 2X3X4 array of integers. Elements are uninitialized.
Array<int, 2, 3, 4> a, b;
Array<short, 2, 3, 4> c;
Array<int, 0> e1; // This line must cause a compile-time error.
如何实现此功能?我想如果我可以提取所有参数列表,那么我可以创建n维数组作为直接递归调用。我现在该怎么办
答案 0 :(得分:4)
您可以创建一个符合您需要的编译时特征:
#include <type_traits>
template <std::size_t... Ts>
struct not_zero {};
template <std::size_t N>
struct not_zero<N> : std::integral_constant<bool, N> {};
template <std::size_t N, std::size_t... Ts>
struct not_zero<N, Ts...> : std::integral_constant<bool, N && not_zero<Ts...>::value> {};
template <typename T, std::size_t... Ts>
struct Array
{
static_assert(not_zero<Ts...>::value, "Dimension cannot be 0");
};
template struct Array<int, 3>; // OK
template struct Array<int, 3, 2, 1, 0>; // error: static assertion failed: Dimension cannot be 0
查看演示here。
答案 1 :(得分:2)
这样的事可能
namespace mine {
template<typename T, size_t first, size_t... rest>
struct multi_array__ {
enum { dims = sizeof...(rest) };
static_assert(first,"dimension can not be zero!");
typedef std::array< typename multi_array__<T, rest...>::type, first > type;
};
template<typename T, size_t first>
struct multi_array__<T,first> {
enum { dims = 1 };
static_assert(first,"dimension can not be zero!");
typedef std::array<T,first> type;
};
template <typename T, std::size_t... ds>
using multi_array = typename multi_array__<T, ds ...>::type;
};
您可以像这样使用
mine::multi_array <int,2,3,4> arr1 = {};
// multi_array<int,2,3,0,4> arr3; // This fails
mine::multi_array <int,3,4> arr2 = {};
这样的作业也是如此
arr2[0] = arr1[0][0];
Here
是一个简单的测试程序。
答案 2 :(得分:2)
为它创建专业化:
#include <iostream>
template <typename T, std::size_t... Dims>
struct Array {};
template <typename T>
struct Array<T, 0>; // leave as an incomplete type
int main()
{
Array<int, 3> x; // OK
Array<int, 0> y; // error: aggregate ‘Array<int, 0u> y’ has incomplete type and cannot be defined
}