V Hi,I added an operator overloader in my templateclass:graph.h:template <class NODE>class Node{friend ostream &operator<< (ostream &, Node<NODE> &); //line 80NODE* info;[snip]}graph.cpp:[snip]template <class NODE>ostream &operator<<(ostream &output, const Node<NODE> &node){output << *(node.info) << " ";return ouput;}[snip}While compiling with gcc I get the warning:In file included from graph.cpp:2:.../graph.h:80: warning: friend declaration `std::ostream&operator<<(std::ostream&, Node<NODE>&)'' declares anon-template function.../graph.h:80: warning: (if this is not what you intended, make sure thefunction template has already been declared and add <> after thefunction name here) -Wno-non-template-friend disables this warningWhat is the reason for that warning and how can I avoid it?Thank you.Regards,Chris 解决方案Declare your operator<< as a template before the class template. Seeabove.V Add here: template<class NODE> class Node; template<class NODE> ostream& operator<<(ostream&, Node<NODE>&);Why are these declarations necessary? I notice that neither VS 2003 nor VC++6.0 needs them.DW Why are these declarations necessary? I notice that neither VS 2003 nor VC++ 6.0 needs them.The Standard, in 14.5.3/1, says that if the friend function declarationthat is not a template declaration (does not begin with the ''template''keyword) and the name of the function is a template-id, the frienddeclaration refers to a template specialisation, if it''s not a template-idbut an ''unqualified-id'', it declares an ordinary function. So, if you (orthe OP) don''t declare operator<< as a template beforehand, it isconsidered a simple function, which goes against the fact that its secondargument depends on ''NODE''.The conflict is resolved if ''operator<<'' is a template-id, which isachieved by declaring ''operator<<'' a template (that''s the second templatedeclaration above ''Node''). The declaration of ''Node'' as a class template(the very first declaration statement) is necessary because it''s used inthe following function template declaration. DWV 这篇关于运算符在模板中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-16 00:29