简体   繁体   中英

Overloading << with templates: Why am I getting the following error?

 template <typename T> class Queue
{

template<typename T> ostream& operator<< (ostream& print, const Queue <T>& x)
   {
        print<<"\nThe elements are as : \n";
        if(q.f!=-1)
        {
            int fr=q.f,rr=q.r;
            while(fr<=rr)
                print<<q.q[fr++]<<" <- ";
        }
        print<<endl;
    }
  //other stuffs
};

  In main():
  Queue<int> q(n); //object creation
  cout<<q; //calling the overloaded << function

It is giving me the following error:

C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|16|error: declaration of 'class T'|
C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|3|error:  shadows template parm 'class T'|
C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|16|error: 'std::ostream& Queue<T>::operator<<(std::ostream&, const Queue<T>&)' must take exactly one argument

In order to use:

Queue<int> q(n);
cout << q;

The function

ostream& operator<<(ostream& print, const Queue <T>& x)

needs to be defined as a non-member function. See my answer to another question for additional information on this particular overload.

Declaring a friend function is tricky for class templates. Here's a bare bones program that shows the concept.

// Forward declaration of the class template
template <typename T> class Queue;

// Declaration of the function template.
template<typename T> std::ostream& operator<< (std::ostream& print, const Queue <T>& x);

// The class template definition.
template <typename T> class Queue
{

   // The friend declaration.
   // This declaration makes sure that operator<<<int> is a friend of Queue<int>
   // but not a friend of Queue<double>
   friend std::ostream& operator<<<T> (std::ostream& print, const Queue& x);
};

// Implement the function.
template<typename T> 
std::ostream& operator<< (std::ostream& print, const Queue <T>& x)
{
   print << "Came here.\n";
   return print;
}

int main()
{
   Queue<int> a;
   std::cout << a << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM