Mar*_*dik 5 c++ templates warnings
当我执行以下操作时:
template <typename T>
class Container
{
public:
class Iterator
{
friend bool operator==(const Iterator& x, const Iterator& y);
};
};
Run Code Online (Sandbox Code Playgroud)
gcc给了我以下警告和建议:
warning: friend declaration
'bool operator==(const Container<T>::Iterator&,
const Container<T>::Iterator&)'
declares a non-template function [-Wnon-template-friend]
friend bool operator==(const Iterator& x, const Iterator& y);
^
(if this is not what you intended,
make sure the function template has already been declared
and add <> after the function name here)
Run Code Online (Sandbox Code Playgroud)
我很确定这是一个新的警告,因为我总是这样做,从来没有任何问题.
有人可以解释为什么这是一个警告,它警告什么?
它警告说,实际上不可能定义那种operator==课外.
也就是说,该friend声明与非模板operator==函数Container<Int>::Iterator成为朋友- 例如,作为朋友具有该函数
bool operator==(const Container<Int>::Iterator&, const Container<Int>::Iterator&);
Run Code Online (Sandbox Code Playgroud)
这个函数不是模板,因此几乎没有办法为类模板定义之外的operator==所有可能的Containers定义.
如果你试图这样做
template<class T>
bool operator==(const Container<T>::Iterator&, const Container<T>::Iterator&);
Run Code Online (Sandbox Code Playgroud)
这是一个函数模板,与友元声明不匹配.(在这种情况下,情况更糟,因为您实际上无法使用此运算符,因为T它位于非推导的上下文中.)
警告消息提示了一种可能的解决方法 - 首先声明一个函数模板,然后与它进行特化.(您需要Iterator将类拉出到自己独立的类模板中,以便T可以推导出来.)另一种可能的解决方法是在类模板定义中定义函数.