
"Phil Endecott" <spam_from_boost_dev@chezphil.org> writes:
http://www.gamedev.net/community/forums/topic.asp?topic_id=261920
Yes, a very good page showing several solutions:
1. A vector of member pointers (may have some overhead). 2. Anonymous structs and unions (may be non-standard). 3. x, y and z implemented as references (makes object bigger). 4. Relying on (&x)[1] pointing to y.
Regarding (2), note that using a union can cause severe performance degradation with some compilers (recent versions of gcc, at least). I guess that the compiler makes pessimistic assumptions about aliasing when it sees a union. As an example: I have some code that offers both ".x/.y/.z" and array-style access to the members of 3d vectors. The code originally only used ".x/.y/.z" fields. When I first added the "array-style" feature, I used a construct like: union { struct { float x, y, z; }; float els[3]; }; float &operator[] (unsigned i) { return els[i]; } const float &operator[] (unsigned i) const { return els[i]; } The resulting object code was _much_ worse than the original. I subsequently changed the code to use your option (4): T &operator[] (unsigned i) { return (&x)[i]; } const T &operator[] (unsigned i) const { return (&x)[i]; } And the resulting object code was much better -- basically the same as the original .x/.y/.z fields-only code. [I guess that doing this could potentially cause the compiler to miss some aliasing that it shouldn't, but in practice this isn't a problem, as all my code uses either the field-style access or array-style access, and never mixes the two.] Option (3) doesn't really seem practical to me given that such small vectors are used very heavily, and often in great numbers. I dunno about option (1): on first glance, it looks even more hacky than the other options, and the the use of a global variable seems like it might cause pessimal assumptions by the compiler (though at least, hopefully, that would only affect the array-style access, not all access like option (2) does). -Miles -- "Suppose He doesn't give a shit? Suppose there is a God but He just doesn't give a shit?" [George Carlin]