template <class ElemType>class TreeNode{public : ...... template <class T> void SwapLR (TreeNode <T>* t);private: ......};
類模板中的友元聲明還是有點講究的。
最初的代碼如下所示:
template <class ElemType>class TreeNode{public : ...... friend void SwapLR (TreeNode <ElemType>* t);private : TreeNode <ElemType>* left, *right;};
在codeblocks下面寫的,用gcc編譯,出現如下警告和錯誤:
warning: friend declaration 'void SwapLR (TreeNode<ElemType>*)'declares a non-template function|
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) |
error: 'TreeNode<char>* TreeNode<char>::left' is private within this context
error: 'TreeNode<char>* TreeNode<char>::right' is private within this context
後來看了《C++ Primer 特別版》的第16章“類模板中的友元聲明”才知道怎麼回事。第一次修改如下:
template <class ElemType>class TreeNode{public: ...... template <class ElemType> friend void SwapLR (TreeNode <ElemType>* t);private: ......};
編譯一下,還是有錯誤:
error: declaration of 'class ElemType' shadows template parm 'class ElemType'|
好吧,再次修改:
template <class ElemType>class TreeNode{public : ...... template <class T> friend void SwapLR (TreeNode <T>* t);private : ......};
相信你已經看出來了,沒錯,就是把友元聲明時使用的模板聲明中的ElemType類型換成T類型,從而避免shadow錯誤。