Recently I started to use unity3d for my hobby game project and I really liked a Vector3 (and similar) classes (in C#). At the moment at work I am implementing a simple (but for large simulations) SPH solver. What I would like to achieve is a similar Vector3 class in C++ in the means of access to elements both by v.x, v.y, v.z and v[0], v[1], v[2]. In general to obtain this is very simple, but none of the solutions that came to my mind is free of flaws.

**Solution 1**: using references &x, &y, &z, problem: such class has three additional variables which occupy the memory. In the case of large simulation it is problematic:

template <class T> class Vector3 { public: T &x,&y,&z; T v[3]; Vector3(): x(v[0]), y(v[1]), z(v[2]) { v[0]=0; v[1]=1; v[2]=2; } T& operator[](int i) { return v[i]; } };

The access is very elegant:

v[i]

as well as

v.x, v.y and v.z

And this is what I woluld like to obtain - this elegant access. However the additional memory overhead is unacceptable.

**Solution 2**: using class fileds x,y,z and access operator with if statement: problem performance of [] operator

template <class T> class Vector3 { public: T x,y,z; Vector3(): x(0), y(1), z(2) { } T& operator[](int i) { if (i==0) return x; else if (i==1) return y; else if (i==2) reurn z; else { //throw access error } } };

This solution is elegant as well, but the operator [] will be very slow.

**Solution 3**: Using the class functions x(), y(), z()

template <class T> class Vector3 { public: T v[3]; Vector3() { v[0]=0; v[1]=1; v[2]=2; } T& operator[](int i) { return v[i]; } T& x() { return v[0]; } T& y() { return v[1]; } T& z() { return v[2]; } };

This solution is ideal in means of efficiency and memory overhead, but, does not allow elegant access to members, requires for example v.x() instead of v.x.

The question is: is there a way to obtain this elegant access with no efficiency and memory loss?