struct myStruct{
int x, y, z;
int operator [](int index){
return (&x)[index];
}
}
myStruct s;
s.x = 0;
and
struct myStruct{
int a[3];
int operator [](int index){
return a[index];
}
int x(void){
return a[0];
}
int y(void){
return a[1];
}
int z(void){
return a[2];
}
};
myStruct s;
s.a[0] = 0;
are nearly equivalent in terms of speed on modern compilers. The problem arises when I need to access it by subscript, and also use it like an array of floats (like with OpenGL). However, which is more tedious to use:
1. Ensuring that every platform supports telling the compiler how to align and pad the members so that one can make an unsafe cast of the address of the first member to a pointer type, so that it can be subscripted or returned, and being able to refer to each member by their name
or
2. Storing the members as an array, allowing me to return a pointer and subscript safely and reliably, and providing an inlined x(), y(), and z() member function that returns a[0], a[1], and a[2] respectively
?
I'd prefer the second, as deterministic type safety seems like a better choice.
The downfalls of each, as far as I can tell:
1. Requiring alignment and padding to both be controlled the same way no matter what compiler (if the compiler can't or doesn't do it right, the program could crash!), and unsafe cast from a single member to a pointer of its type, knowing it will be accessed like an array.
2. Takes a couple more keystrokes to access the data (s.a[0] or s.x() vs s.x), and a little tougher to conceptually grasp.
I believe that a properly inlined s.x() or s.a[0] would be just as fast/slow as s.x; both would dereference a this pointer, and both would use a constant offset from the beginning of the struct (and possibly array) to reach the data, so it seems like it makes no difference in speed.
The pros of each:
1. Simple to use and understand; behaves how you expect a vector class might.
2. Performs reliably, and safely.
Which would be preferable, knowing that my goal is portability, and reliability (I'd rather not depend on compiler pragmas, macros, and settings)? Does the array method have any serious implications, like speed?