I have a vector class
class vec3
{
public:
FLOAT x, y, z;
vec3(FLOAT X = 0, FLOAT Y = 0, FLOAT Z = 0)
{
x = X;
y = Y;
z = Z;
}
};
And I need to be able to use this vector as either spacial dimension using x, y, z, or as color using r, g, b or as measure dimensions using w, h, l.
It would be a waste of memory to have this vector class containing 9 members. Instead I want it to contain x, y and z and refer to them as stated above.
I already searched online and found almost fitting solutions, see C++ member variable aliases?
But the thing is, if I use something like
struct Vertex {
float& r() { return values[0]; }
float& g() { return values[1]; }
float& b() { return values[2]; }
float& x() { return values[0]; }
float& y() { return values[1]; }
float& z() { return values[2]; }
float operator [] (unsigned i) const { return this->values_[i]; }
float& operator [] (unsigned i) { return this->values_[i]; }
operator float*() const { return this->values_; }
private:
float[3] values_;
}
then I can only read the struct members, not set them, and if I use
struct vertex
{
private:
float data[3];
public:
float &x, &y, &z;
float &r, &g, &b;
vertex() : x(data[0]), y(data[1]), z(data[2]), r(data[0]), g(data[1]), b(data[2]) {
}
float& operator [](int i) {
return data[i];
}
};
then the struct increases in memory because each reference takes up space.