954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Operator overloading with nested and templated classes

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

cubathy
Newbie Poster
3 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

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->
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

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
}
cikara21
Posting Whiz
340 posts since Jul 2008
Reputation Points: 47
Solved Threads: 69
 

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.

cubathy
Newbie Poster
3 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

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.

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

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...

cubathy
Newbie Poster
3 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You