I am creating my own vector struct for a maths library.
Currently, I would create the struct somewhat like this:
template <unsigned int size, typename T>
struct vector {
// array of elements
T elements[size];
// ...
};
However, the main use case of the maths library will lead to mostly making use of 2-dimensional, 3-dimensional, and 4-dimensional vectors (commonly vec2
, vec3
, and vec4
). Because of this, a useful feature would be the ability to access the x, y, z, and w values from the vector when possible. However, there are some problems with this.
The x
, y
, z
, and w
members would need to be reference variables to elements[0]
, elements[1]
, etc. This means that, if the vector has less than 4 elements, some references would not be initialised.
Of course, this is possible to achieve with specialised templates, and this is what I am currently doing:
template <unsigned int size, typename T>
struct vector {
// ...
}
template <typename T>
struct vector<2, T> {
// same as with before, except with references to X and Y elements.
// these are successfully initialised in the constructor because the vector is guaranteed to have 2 elements
T &x;
T &y;
// ...
}
// and so on for 3D and 4D vectors
This works, but it is far from convenient. In practice, the vector
struct is large and has a lot of functions and operator overloads. When it is specialised into the other sizes, these functions and operator overloads need to be copy+pasted from the generic struct to 2D, 3D and 4D structs, which is very inefficient. Keep in mind: the only thing I'm changing between specialisations is the reference variables! All other members are the exact same, and so I'd rather reuse their code.
One other solution is to inherit from one base class. I'm not entirely sure how to do this in a way that allows the inherited operator overloads to return the values from the child vector structs rather than the values from the parent struct.
So, my question is: how would I efficiently reuse the code in a specialised template struct whilst still being able to have (in this case) the x
, y
, z
, and w
references, when available?