I made a lot of vector math materials and wrote my own template for myself.
My requirements are a lot of vector mathematical calculations (addition, subtraction, scale, cross prod and dot prod), I also need to pass my vector as float [] so that openGL can use it.
I used it quite happily for a while, today the lecturer saw it and groaned. In particular, he hated (one of which I understand), I used inheritance because he did not seem to adhere to is a style. And my casting (T*)this , of course, he didn’t have much of a solution.
First: Inheritance, I should be able to use vec2 for vec4, so I designed my vectors as follows.
template<typename T> Vector2D { public: getX(), getY(), setX(), setY() .... }; template<typename T> Vector3D : public Vector2D<T> { public: getZ(), setZ() ... } template<typename T> Vector4D : public Vector3D<T> { public: getW(), setW() ... }
Why is that bad? and tbh I don’t see how to improve it. I need (want) to be able to determine the type and have some getters and setters. If I rebuilt it as
template<typename T, int _size> VectorT
I would lose my stuff .getX() , .setX() and had to replace it with something like .at() or [] . tbh I prefer the readability of .getX() , although this will make it easier to define operators.
Second: I see why this is bad, but to do this, I can pass these vectors to the openGL method, expecting a floating-point array, which I overloaded the splat operator
// Defined in Vector2D<T> operator*() { return (T*)this; }
As I understand it, there is no guarantee that the compiler will put the x, y, z, w member variables at the beginning of the class, and if not careful, I can end up passing the v-table. However, I must admit that so far I have not had any problems.
The only way I can see is to maintain an array that is returned. Most likely, it would be easier if I changed them the way I primarily relate to vectors.