Home > Mobile >  What is the syntax for overloading the assignment operator (=) for a nested template class in a .cpp
What is the syntax for overloading the assignment operator (=) for a nested template class in a .cpp

Time:04-02

I am trying to overload an assignment operator in a cpp file for a nested template class.

My header file looks something like this:

template <class T>
class Outer:
private:
   // some member variables
public:
   /*
   * Other functions here
   */

   template <class T>
   class Inner:
      Inner & Inner :: operator = (const Inner & rhs);

I can't, however, figure out what my cpp file should look like. This is what I have:

template <class T>
Outer<T>::Inner<T>:: Inner<T> & Inner<T> :: operator = (const Inner<T> & rhs)
{
   // code is here
}

This gives me the error:

Iterator is not a template (C/C 864)

on the parts of my code surrounded by *

Outer<T>::Inner<T>::Inner<T> & **Inner<T>** :: operator = (const **Inner<T>** & rhs)

I would rather not make the operator overloads inline if I can avoid it. Help!

CodePudding user response:

Class template must be defined in header file. I am not sure to understand the question but the below code compile:

template <class T>
class Outer {
 public:
  template <class V>
  class Inner {
    Inner& operator=(const Inner& rhs);
};
};

template <class T>
template <class V>
Outer<T>::Inner<V>& Outer<T>::Inner<V>::operator=(const Outer<T>::Inner<V>& rhs) {
  //do something
   return *this;
}

int main() {
        Outer<int> o;
}

CodePudding user response:

Working Header File:

template <class T>
class Outer
{
private:
   // some member variables
public:
   /*
   * Other functions here
   */

   class Inner
   {
   private:
      T t;
   public:
      Inner & operator = (const Inner & rhs);
   };
};

Working cpp file:

template <class T>
Outer<T>::Inner & Outer<T>::Inner::operator = (const Inner & rhs)
{
   // code is here
}
  •  Tags:  
  • c
  • Related