I am using Visual C on Windows 10.
I want to make class Vector4
such that it has members x, y, z, t
and they stored contiguously to provide operator[]
and other functions:
class Vector4
{
public:
float operator[](size_t idx)
{
return &x idx;
}
public:
float x, y, z, t;
}
But I found out that such implementation works not on every compiler(On Visual C it works well).
And I dont know how to fix it, maybe write something like this: class alignas(sizeof(float)) Vector4;
CodePudding user response:
From: C - Class contiguous data
You can use #pragma pack(1) with e.g. MSVC and gcc, or #pragma pack 1 with aCC.
As said in the answer #pragma pack(1)
will disables padding and guarantees that the members are contiguous:
That basically disables padding and guarantees that the floats are contiguous. However, to ensure that the size of your class is actually 4 * sizeof(float), it must not have a vtbl, which means virtual members are off-limits.
See also the official C documentation: Implementation defined behavior control
The answer gives two ways:
#pragma pack(1)
class FourFloats
{
float f1, f2, f3, f4;
};
and
#pragma pack(push, 1)
class FourFloats
{
float f1, f2, f3, f4;
};
#pragma pack(pop)
CodePudding user response:
I have the same need, and I did something like this:
class Vector4
{
public:
// This is our data (4 doubles)
union {
double data[4]; // access as an array
struct {
double x; // access as individual values
double y;
double z;
double t;
};
};
public:
// default construct
Vector4() : data{ 0, 0, 0, 1 }{}
// construct from 4 doubles
Vector4(const double& x, const double &y, const double& z, const double & t) :
x(x), y(y), z(z), t(t){}
// const and non-const [] operators
double& operator[](const size_t Index){ return data[Index]; }
double operator[](const size_t Index) const { return data[Index]; }
};
This will allow accessing by [] or by .x, .y, etc.
Vector4 my_vec(1.1, 2.2, 3.3, 1.0);
auto x = my_vec.x;
auto y = my_vec[1];
I also implemented many other useful functions, such as dot product, cross product, etc.