Hi everyone. Getting compile errors with the following code that i can not figure out...:

template <class T>
class X{

	class Y{





template <class T>
typename X<T>::Y * operator[](X<T> * obj1, int index);

The compile error from mingw is:

test.h:18: error: 'typename X<T>::Y * operator[](X<T> * obj1, int index);' must be a nonstatic member function

Can anyone explain why this doesn't compile and if/how I can get round the problem? Thanks

Read the compiler message: operator [] MUST be non-static member of a class. No operator[] in X class definition.
Three operators must be non-static members in C++:


Is this what u need..

template<class T>class X
   class Y
      //...Declare it first
      Y *operator[](int);
template<class T>typename
X<T>::Y *X<T>::Y::operator[](int idx)

I was actually trying to make the following possible:

X<int> * x = new X<int>();
x::Y * y = x[0];

Or something along those lines... i.e. operator[] for the pointer type so you don't have to use (*x)[0]. But seems like that's not possible if it has to be a non-static member?? Any other way to accomplish that? X is actually abstract so need to store as pointer to X, but still want to use [] operator.

Thanks for responses so far.

Of course, you can't redefine pointers behaviour in C++ (thank God! ;) ). See what you want to do (and, fortunately, can do):

template <typename T>
class X {
    ~X() { cout << "RIP X" << endl; }
    class Y {
        void whoareyou() const {
            cout << "It\'s me, Boss!" << endl;
    Y* operator[](int i) { return y+i; } //!!!
    Y y[2];

int main()
    X<int>& x = *new X<int>(); // a reference, not a pointer to!
    X<int>::Y* py = x[0];
    delete &x;

Try this and see what happens.

Thanks ArkM - it's compiling at least :). Think I need to read up a bit on references before I trust myself to use them like this though...