I have a bunch of vector classes. I have a 2D point vec2_t
, a 3D point vec3_t
and a 4D point vec4_t
(you often want these when you have do graphics; this is graphics code, but the question has a generic C++ flavour).
As it is now, I have vec2_t
declaring two members x
and y
; vec3_t
subclasses vec2_t
and has a third member z
; vec4_t
subclasses vec3_t
and adds a w
member.
I have a lot of near-duplicate code for operator overloading computing things like distances, cross products, multiplication by a matrix and so on.
I've had a few bugs where things have been sliced when I've missed to declare an operator explicitly for the subclass and so on. And the duplication bugs me.
Additionally, I want to access these members as an array too; this would be useful for some OpenGL functions that have array parameters.
I imagine that perhaps with a vec_t<int dimensions>
template I can make my vector classes without subclassing. However, this introduces two problems:
- How do you have a variable number of members that are also array entries, and ensure they align? I don't want to lose my named members;
vec.x
is far nicer thanvec.d[0]
or whatever imo and I'd like to keep it if possible - How do you have lots of the more expensive methods in a CPP source file instead of the header file when you take the templating route?
One approach is this:
struct vec_t {
float data[3];
float& x;
float& y;
float& z;
vec_t(): x(data[0]), y(data[1]), z(data[2]) {}
};
Here, it correctly aliases the array members with names, but the compiler I've tested with (GCC) doesn't seem to work out they are just aliases and so the class size is rather large (for something I might have an array of, and want to pass e.g. as a VBO; so size is a big deal) and how would you template-parameterise it so only the vec4_t
had a w
member?)