3

我有一个具有以下规范的模板类:

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 维数组创建为直接递归调用。我现在该怎么做

4

3 回答 3

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

在此处查看演示。

于 2013-05-12T19:20:24.483 回答
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是一个简单的测试程序。

于 2013-05-12T18:27:45.837 回答
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
}
于 2013-05-12T18:32:36.390 回答