[英]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.声明friend
函数对于类模板来说很棘手。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.