I am creating a vector class and trying to figure out ways to reuse the maximum amount of code for different size vectors. Here is a basic example:
template<typename T, unsigned int D> class Vector { public: union { T v[D]; struct { }; }; Vector() { for(unsigned int i=0; i<D; ++i) (*this)[i] = T(0); } Vector(T scalar) { for(unsigned int i=0; i<D; ++i) (*this)[i] = scalar; } inline T operator[](int i) { return (*this).v[i]; } };
I want member variables to be publicly available. Example:
Vector<float,2> vec; printf("X: %.2f, Y: %.2f\n", vec.x, vec.y);
What I would like to do is something like this:
template<typename T> class Vector2 : public Vector<T,2, struct { T x; T y; }> {}; template<typename T> class Vector3 : public Vector<T,2, struct { T x; T y; T z; }> {};
and redefine the structure in the union:
template<typename T, unsigned int D, struct C> class Vector { public: union { T v[D];
Is there any possible way to do this? I do not want to use anything other than the standard library, if possible. Thanks in advance.
EDIT: After reading all the answers, I realized that the way you use unions is wrong! Thanks @MM for this. Since then, I have chosen a different route, but I have chosen the answer that best matches what I was looking for at that time. Thank you again for all the welcome answers below!