[英]friend operator<< in template class
據我了解的朋友功能,這應該工作。 我不確定發生了什么。
在我的代碼中,我定義了一個類
template < class IType = unsigned int >
class BitArray {
...
friend ostream& operator<<(ostream&, const BitArray&);
friend istream& operator>>(istream&, BitArray&);
...
}
然后在同一個頭文件中
template < class IType >
ostream& operator<<(ostream& os, const BitArray<IType>& that)
{
...
}
template < class IType >
istream& operator>>(istream& is, BitArray<IType>& that)
{
...
}
這給了我
error LNK2019: unresolved external symbol
當我嘗試編譯時。
我已經重新閱讀並重新編寫了六遍,並查看了“ friend”關鍵字的使用,但找不到問題所在。
由於模板,此實現是否遵循不同的規則
我也重寫了<<和>>作為移位運算符,但同樣不要緊,因為它們具有不同的參數。
發出警告后,您將:
warning: friend declaration 'std::ostream& operator<<(std::ostream&, const BitArray<IType>&)' declares a non-template function [-Wnon-template-friend]
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
因此,在聲明模板函數之前:
template <class IType> class BitArray;
template <class IType> std::ostream& operator<<(std::ostream&, const BitArray<IType>&);
template <class IType> std::istream& operator>>(std::istream&, BitArray<IType>&);
template < class IType = unsigned int >
class BitArray {
friend std::ostream& operator<< <>(std::ostream&, const BitArray&);
friend std::istream& operator>> <>(std::istream&, BitArray&);
};
template <class IType>
std::ostream& operator<<(std::ostream& os, const BitArray<IType>& b)
{
/* Your implementation */
}
我想你想要這個:
template < class IType = unsigned int >
class BitArray {
template<class> friend ostream& operator<<(ostream&, const BitArray&);
template<class> friend istream& operator>>(istream&, BitArray&);
};
您的BitArray聲明告訴編譯器尋找非模板運算符<<和operator >>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.