我有一个重载运算符<<的模板方法。我需要在调用类中的方法时调用该运算符。但是当我尝试时,它会给我一些编译错误。
这是来自名为 BTreeLeave 的具体类的方法
bool BTreeLeave::burn() {
csv::WriterStream os("products.txt", std::ios_base::out);
os.set_delimiter(',');
if (os.is_open()) {
os << 1693 << NEWLINE;
os << 15 << 16 << 17 << 20 << NEWLINE;
os << "s" << "i" << "f" << NEWLINE;
os << 2 << NEWLINE;
os << "+" << NEWLINE;
os << "0" << NEWLINE;
}
模板函数就是这个
template<typename T>
typename csv::WriterStream& operator << (typename csv::WriterStream& ostm, const T& val)
{
if(!ostm.get_after_newline())
ostm.get_ofstream() << ostm.get_delimiter();
ostm.get_ofstream() << val;
ostm.set_after_newline(false);
return ostm;
}
template<>
inline csv::WriterStream& operator << (typename csv::WriterStream& ostm, const char& val)
{
if(val==NEWLINE)
{
ostm.get_ofstream() << NEWLINE;
ostm.set_after_newline(true);
}
else
ostm.get_ofstream() << val;
return ostm;
}
我得到的错误是'csv::WriterStream' 不是从 'std::basic_ostream 派生的和"与'运算符<<'不匹配(操作数类型为'csv::WriterStream'和'int')"
如果我尝试从主函数调用<<运算符是可以工作的。我做错了什么?
你试试下面的定义
template<typename T>
typename csv::WriterStream& operator << (typename csv::WriterStream& ostm, T val)
{
if(!ostm.get_after_newline())
ostm.get_ofstream() << ostm.get_delimiter();
ostm.get_ofstream() << val;
ostm.set_after_newline(false);
return ostm;
}