Quote:Original post by bobstevens
but really this solves a problem that doesn't exist
Or the problem isn't apparent to you, indeed it is very subtle and i should have probably explained at the beginning but it does solve a problem, actually it solves two problems.
1. if you use the union method using
standard compliant c++ code you'll end up with something like this:
#include <cstddef>#include <iostream>template< typename T >struct vector4 { typedef size_t size_type; struct vec { T x, y, z ,w; }; typedef typename vector4<T>::vec vec_type; union { T v[4]; vec_type g; }; const T& operator[](size_type i) const { return v; } T& operator[](size_type i) { return v; }};template< typename T >struct matrix4 { typedef size_t size_type; union { vector4<T> vec[4]; vector4<T> i, j, k, l; }; const vector4<T>& operator[](size_type i) const { return vec; } vector4<T>& operator[](size_type i) { return vec; }};int main() { matrix4<int> m; m[0][0] = 10; std::cout << "m[0][0]: " << m[0][0] << '\n'; std::cout << "m[0].g.x: " << m[0].g.x << '\n'; std::cout << "m.i.g.x: " << m.i.g.x << '\n'; return 0;}
from that code notice this part of the code:
matrix4<int> m;m[0][0] = 10;std::cout << "m[0][0]: " << m[0][0] << '\n';std::cout << "m[0].g.x: " << m[0].g.x << '\n';std::cout << "m.i.g.x: " << m.i.g.x << '\n';
VS using pointer to data member version:
matrix4<int> m;m[0][0] = 10;std::cout << "m[0][0]: " << m[0][0] << '\n';std::cout << "m[0].x: " << m[0].x << '\n';std::cout << "m.i.x: " << m.i.x << '\n';
which one looks more natural to work with?
2. Fine fair enough so just say for a minute you started with the union method later on you decide that you wont to make some constructors in you main vector type using constructor initializer lists using the non-array members i.e. vec x, y, z, w, the only way you can do this is by giving the internal structure vec a constructor aswell but this also isn't standard compliant code because union members are not suppose to have constructors & destructors.
pointer to data members are not hacks, its completely legitimate standard compilant code & is probably safer than using public unions.
Quote:Original post by bobstevens
that's incomprehensible.
you can easily make the "incomprehensible" part private not the case with unions so much [smile]
[Edited by - snk_kid on August 29, 2004 9:52:21 AM]