简体   繁体   English

C ++:具有任意数量的初始化参数的模板类/函数

[英]C++: template class/function with any number of initializing arguments

I'm trying to create template class of a vector in geometry of arbitrary number of dimensions. 我正在尝试在任意数量尺寸的几何图形中创建矢量的模板类。 I would like to create an intuitive constructor where I can pass number of initializers equal to dimension number. 我想创建一个直观的构造函数,在该构造函数中我可以传递与维数相等的初始值设定项。 For example: 例如:

template<int dim = 3, typename float_t=double> class Vec{
    float_t x[dim];
public:
    Vec(...) {
        //some template magic
    }
};


int main() {
    typedef Vec<3> Vec3d;
    typedef Vec<2> Vec2d;

    double x=1,y=2,z=3;
    Vec3d v(x,y,z);
    Vec2d w(x,y);
}

Now I lack the knowledge of black magic - I mean the C++ templates. 现在我缺乏黑魔法的知识-我的意思是C ++模板。 How I should write this example to get my goal? 我应该如何写这个例子来实现我的目标? Of course I don't want to write every exact constructor for every case, that's not the spirit of C++ templates - and I'm really interested how to accomplish that in the smart way. 当然,我不想为每种情况编写每个确切的构造函数,这不是C ++模板的精神-我真的很感兴趣如何以一种聪明的方式完成它。

You need a parameter pack : 您需要一个参数包

template <typename... Args>
Vec(Args... args) : x{args...} {
    static_assert(sizeof...(Args) == dim, "Number of parameters should match dimension");
}

I'm also using static_assert to make sure the user enters the right number of parameters matching the dimension. 我还使用static_assert来确保用户输入与维数匹配的正确数量的参数。

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

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