Ch3*_*ire 2 c++ templates c++11
我正在尝试在任意数量的维度的几何中创建矢量的模板类.我想创建一个直观的构造函数,我可以传递一些等于维数的初始值设定项.例如:
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);
}
Run Code Online (Sandbox Code Playgroud)
现在我缺乏黑魔法的知识 - 我的意思是C++模板.我应该如何编写这个例子来实现我的目标?当然,我不想为每个案例编写每个确切的构造函数,这不是C++模板的精神 - 我真的很有兴趣如何以智能的方式实现它.
你需要一个参数包:
template <typename... Args>
Vec(Args... args) : x{args...} {
static_assert(sizeof...(Args) == dim, "Number of parameters should match dimension");
}
Run Code Online (Sandbox Code Playgroud)
我还使用static_assert确保用户输入与维度匹配的正确数量的参数.
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |