繁体   English   中英

可变参数模板和构造函数

[英]Variadic template and constructor

我正在写一些类,将特定的多维数组映射到一维数组(例如,按M大小排列的2D数组N就像您知道的1D数组N M大小,然后可以通过[n + m N ])。 这很无聊,因为我必须处理任何多维数组(被迫多次复制/粘贴类定义)。

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

问题是我不知道该怎么做:(我发现的每个示例都依赖于两个函数,一个带有一个参数类型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:
}

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

PS:我可以使用经典的可变参数函数(例如C语言)来做到这一点,但是它的性能会很差:

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

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...} {

    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM