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

template <class T>
class X{

	class Y{

		public:
			Y();

	};

	X();

};


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

Recommended Answers

All 5 Replies

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++:

operator=
operator[]
operator->

Is this what u need..

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

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 {
public:
    ~X() { cout << "RIP X" << endl; }
    class Y {
    public:
        void whoareyou() const {
            cout << "It\'s me, Boss!" << endl;
        }
    };
    Y* operator[](int i) { return y+i; } //!!!
private:
    Y y[2];
};

int main()
{
    X<int>& x = *new X<int>(); // a reference, not a pointer to!
    X<int>::Y* py = x[0];
    py->whoareyou();
    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...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.