Reputation: 1106
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. 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.
Upvotes: 2
Views: 171
Reputation: 3849
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.
Upvotes: 6