可变参数模板和构造函数

时间:2017-01-26 13:27:05

标签: c++ arrays

我正在编写一些将特定多维数组映射到单维数组的类(如M大小的2D数组N就像你知道的1D数组N M大小,然后你可以加入单元格[n,m]通过[n + m N])。由于我必须处理任何多维数组(强制复制/粘贴多次类定义),因此非常无聊。

我发现在我的情况下可能很棒的东西:可变参数模板函数。 我想让我的构造函数和访问器使用可变参数模板,这样我的访问器可以使用任意数量的参数(2个用于2D数组,3个用于3D数组......)和我的构造函数相同,因为我需要在每个参数中保存大小维度(N,M,...)然后乘以得到我的unidimentionnal数组的大小。

问题是我不知道该怎么做:( 我找到的每个示例都依赖于两个函数,一个函数有一个T类型的参数,另一个参数类型为TArgs... args

是否可以在一个功能中使用?没有递归呢? 我告诉你到目前为止我做了什么:

template <typename T, typename... Args>
T returner(T v, Args... args){
    return v;
}

template <typename T>
class Array{

    public:
    int* dim; //contain the size of each dimension
    T* array; //the actual array

    template<typename... Args>
    Array(Args... args){
        constexpr int size = sizeof...(Args);
        dim = new int[size];
        for(int i=0; i<size; i++)
            dim[i] = returner(args...);
            /*dim[0] should be equal to the first argument, dim[1]
            should be equal to the second argument and so on */
    }
};

int main(){
    Array<int>(2,2,2); // meant to be a 3D array, 2cells in each dimension
    return 0:
}

显然,“返回者”总是返回第一个参数并且我理解为什么,但我认为唯一的解决方案是将dim数组作为参数传递,我不想这样做。有解决方案吗?

PS:我可以用经典的可变参数函数来做到这一点,就像在C中一样,但它在性能上会非常糟糕:(

1 个答案:

答案 0 :(得分:2)

这应该做你想要的(如果我理解正确的话):

template <typename T>
class Array{

    public:
    int* dim; //contain the size of each dimension
    T* array; //the actual array

    template<typename... Args>
    Array(Args... args){
        constexpr int size = sizeof...(Args);
        dim = new int[size]{args...};
    }
};

但是你最好使用std::vector而不是原始指针 - 这会为你省去很多麻烦:

template <typename T>
class Array{

    public:
    std::vector<int> dim; //contain the size of each dimension
    std::vector<T> array; //the actual array

    template<typename... Args>
    Array(Args... args) : dim{args...} {

    }
};