I want to write a vector type of arbitrary dimension. The catch is I want to have separate fields for certain dimensions (eg: x,y,z), my solution is to use CRTP to mix in the functionality I need:
#include <unistd.h>
template <typename B, typename T, int DIM>
struct _veccore {
// convert vector to array of underlying scalar type
T* data(ssize_t ii) { return (static_cast<T*>(this))[ii]; }
B operator +(const B& ov) {
B b = reinterpret_cast<B*>(*this);
for (ssize_t ii=0; ii < DIM; ii++) {
b.data(ii) += ov.data(ii);
}
return *this;
}
};
template <typename T> struct _vector1d : _veccore<_vector1d<T>, T, 1> { T x; };
template <typename T> struct _vector2d : _veccore<_vector2d<T>, T, 2> { T x,y; };
template <typename T> struct _vector3d : _veccore<_vector3d<T>, T, 3> { T x,y,z; };
int main() {
_vector1d<float> v1f;
_vector2d<float> v2f;
_vector3d<float> v3f;
}
I believe it's safe based on:
- If T is POD then the _vectorNd types are POD (trivally copyable and standard layout)
- Since it's POD, it has to be C compatible, and C requires storing fields in the order they're declared, so reordering isn't allowed.
Any other gotchas that would make this unsafe?