重载<< with templates:为什么我收到以下错误?

时间:2016-10-09 05:45:15

标签: c++ templates operator-overloading

 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

它给了我以下错误:

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

1 个答案:

答案 0 :(得分:1)

为了使用:

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

功能

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

需要定义为非成员函数。有关此特定过载的其他信息,请参阅my answer to another question

为类模板声明friend函数很棘手。这是一个显示概念的裸骨计划。

// 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;
}