【发布时间】:2020-09-13 21:38:05
【问题描述】:
我尝试编译以下代码:
class CFileOperations
{
...
template <typename T>
inline void load_and_save_data(std::fstream* stream, T& value, const EOperation operation)
{
switch (operation) {
case EOperation::OpSave:
*stream << value; <-- here
break;
case EOperation::OpLoad:
*stream >> value; <-- and here
break;
}
}
...
};
我收到以下错误:
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
例如,我这样使用它,数字是一个'int':
this->load_and_save_data(stream, number, operation);
我正在使用 Visual C++ 2019。
根本原因是什么,以及如何解决。有什么想法吗?
【问题讨论】:
-
你必须为 ostream 定义一个
operator<<函数以及你想放在这里的任何类型 -
fstream是从ostream派生出来的,正常的做法是为ostream编写函数,然后在其他流上下文中使用
-
int 版本已经存在,您的错误是由于其他一些自定义类型。错误消息应指定。或者你可能还没有完成
#include <fstream> -
请务必检查编译器在实际错误之前或之后打印的信息性消息,这可能会提供更重要的细节。
标签: c++ templates visual-c++ compiler-errors fstream