How to write an access operator on a typed pointer?

Consider the following template class:

1
2
3
4
5
6
7
8
template <class Real>
class Matrix34
{
public:
	inline Real (* Get())[4] { return mMatrix; }
private:
	Real mMatrix[3][4];
};


The Get() returns a pointer to Real(*)[4].
Instead of using this explicit Get(), I would like to use an operator to access the Real(*)[4]. The thing is, I don't know how to do this, so I am kindly asking for help.
Last edited on
This only returns the first array (of three), so I'm not sure what all this means, but the syntax is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <class Real>
class Matrix34
{
        Real    mx[3][4];

public:
        typedef Real Real4[4];
        Real4* Get() { return mx; }
        operator Real4* () { return mx; }
};

int main()
{
        Matrix34<int> m;
        Matrix34<int>::Real4 *p = m.Get();
        Matrix34<int>::Real4 *q = m;

        return 0;
}
I personally find multidimensional arrays very funky and try to avoid using them whenever possible. kbw's solution is very good, and will work, but if you'd rather avoid 2D arrays completely you can rearrange your matrix class just a hair to save yourself some headaches:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename Real>
class Matrix34
{
public:
  operator Real* () { return mMatrix; }

  // example members
  void Set(int y,int x,Real r)  { mMatrix[y*4+x] = r; }
  Real Get(int y,int x)         { return mMatrix[y*4+x]; }

  // if you still want "mymatrix[y][x]" syntax:
  Real* operator [] (int y)     { return &mMatrix[y*4]; }

protected:
  Real mMatrix[3*4];
};



This is just my personal preference, though. Linear arrays are just so much easier to work with in C++. I avoid multidimensional arrays like the plague.
@kbw: thank you very much. This is exactly what I needed.

@disch: thanks for the effort, I'm linking against an external api that takes two dimensional arrays as input, so I cannot avoid them.
Topic archived. No new replies allowed.