[英]friend operator<< in template class
From what I know about friend functions this should work. 据我了解的朋友功能,这应该工作。 I'm not sure what's going on. 我不确定发生了什么。
In my code i define a class 在我的代码中,我定义了一个类
template < class IType = unsigned int >
class BitArray {
...
friend ostream& operator<<(ostream&, const BitArray&);
friend istream& operator>>(istream&, BitArray&);
...
}
then later in the same header file 然后在同一个头文件中
template < class IType >
ostream& operator<<(ostream& os, const BitArray<IType>& that)
{
...
}
template < class IType >
istream& operator>>(istream& is, BitArray<IType>& that)
{
...
}
and it's giving me 这给了我
error LNK2019: unresolved external symbol
when I try to compile. 当我尝试编译时。
I've re-read and re-written this half a dozen times, and reviewed the use of the "friend" keyword, and can't find what's wrong. 我已经重新阅读并重新编写了六遍,并查看了“ friend”关键字的使用,但找不到问题所在。
does this implementation follow different rules because of the template 由于模板,此实现是否遵循不同的规则
I also overwrote << and >> as shift operators, but again that shouldn't matter since they have different arguments; 我也重写了<<和>>作为移位运算符,但同样不要紧,因为它们具有不同的参数。
With warning up, you have: 发出警告后,您将:
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)
So declare the template function before: 因此,在声明模板函数之前:
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 */
}
I think you want this: 我想你想要这个:
template < class IType = unsigned int >
class BitArray {
template<class> friend ostream& operator<<(ostream&, const BitArray&);
template<class> friend istream& operator>>(istream&, BitArray&);
};
Your BitArray declaration is telling the compiler to look for a non-templated operator<< and operator>> 您的BitArray声明告诉编译器寻找非模板运算符<<和operator >>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.