template <>
class test<int> {
int y;
public:
test(int k) : y(k) {}
friend ofstream& operator<< <test<int>> (ofstream& os, const test<int>& t);
};
template<>
ofstream& operator<< <test<int> > (ofstream& os, const test<int>& t)
{
os << t.y;
return os;
}
上面的代码是int版本中的专用模板测试类 . 我试图重载流运算符<< function . 但它显示错误信息;
C2027:使用未定义类型'std :: basic_ofstream <_Elem,_Traits>'
此外,相同的方法适用于普通函数(不是流运算符<<但我所做的函数)无论如何我们运算符<< ofstream of function in a special template class?
2 回答
你需要包括
在实例化功能模板时 . 也许你只包括在内
此外,你不应该将(静态)朋友定义为模板: https://ideone.com/1HRlZ
请注意,在头文件中使用namespace std'并不是't a good idea to have ',这就是我从示例中删除它的原因 . (当它们包含您的标头时,它可能会导致头文件的用户发生冲突)
这里有很多有趣的问题 . 首先是明显的家务管理
你应该
#include <fstream>
并且不要忘记using namespace std
.operator <<
不应该是模板,它应该是一个重载函数 .os << t.y
为我混淆了编译器(g 4.4.3:"warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:") . 您打算明显将int推送到流中,但编译器注意到int
可以通过构造函数转换为test<int>
,因此它不知道您是否要推送int
或test<int>
. 这是我知道的愚蠢,可以通过构造函数explicit
来解决 .