Boost logo

Boost :

From: Michael Fawcett (michael.fawcett_at_[hidden])
Date: 2006-09-21 08:54:51


On 9/21/06, Olivier Grant <olivier.grant_at_[hidden]> wrote:
> ok, what about this ?
>
> class vector3d_test
> {
> public:
> float x, y, z;
>
> float operator[]( int index ) const
> { return array[index]; }
>
> float & operator[]( int index )
> { return array[index]; }
>
> union
> {
> struct
> {
> float x;
> float y;
> float z;
> } coord;
> float array[3];
> };
> };
>
> but it means you have to call v.coord.x and v[0].

You can get around this using something like this:

template< typename T >
struct Vector4 {

   typedef size_t size_type;

private:

   typedef T Vector4<T>::* const vec[4];

   static const vec v;

public:

   T x, y, z, w;

   Vector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0):
   x(_x), y(_y), z(_z), w(_w) {}

   const T& operator[](size_type i) const {
      return this->*v[i];
   }

   T& operator[](size_type i) {
      return this->*v[i];
   }

};

template< typename T >
const typename Vector4<T>::vec Vector4<T>::v = { &Vector4<T>::x,
&Vector4<T>::y, &Vector4<T>::z, &Vector4<T>::z };

Here's the original discussion from gamedev.net
http://www.gamedev.net/community/forums/topic.asp?topic_id=261920

This wasn't written by me, I just remembered it from there and thought
it might be interesting to you.

--Mike


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk