错误 C2679 二进制"<<":未找到采用类型为 'T' 的右侧操作数的运算符

Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'T'

本文关键字:lt 运算符 类型 操作数 二进制 C2679 错误      更新时间:2023-10-16

我尝试编译以下代码:

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。

根本原因是什么,以及如何解决它。知道吗?

我的错,其中一个调用是使用"类枚举"。当然,>>和<<不是为此定义的。

对于@cdhowie,下面是两个简单性的示例(借助load_and_save_data模板方法(:

这里mMembers是一个std::unorderedmap(参见上面问题中的save_and_load_data,我也有一个用于starndard容器(:

void CHexArea::load_and_save()
{
this->load_and_save_data((char&)mColor);
this->load_and_save_data(mTouchLeft);
this->load_and_save_data(mTouchRight);
this->load_and_save_data(mTouchBottom);
this->load_and_save_data(mTouchTop);
this->load_and_save_data(mMembers);
}

在这里,在首选项中,有两个版本的文件:

void CHexPreferences::load_and_save()
{
if( this->is_loading() ) {
this->reset(); // version's forward compatibility
}
int version = 2;
this->load_and_save_data(version);
this->load_and_save_data(mBoardOrientation);
this->load_and_save_data(mBoardSize);
this->load_and_save_data(mComputerStarts);
this->load_and_save_data(mComputerInitialTurns);
if( version >= 2) {
this->load_and_save_data(mComputerTilesPerTurn);
}
this->load_and_save_data(mDebugFlags);
}

简单明了。

当然,有两个方法(load((save(((是外部接口,并调用上面的那些,但是:1. 它们是库的一部分(无需重写它们,像往常一样 OO(和 2.加载/保存的核心在load_save_data中只编写一次,优点是简单,并具有相应的加载和保存代码(类型、顺序......

当然,也有缺点,但我希望你能看到,有些人认为也有(恕我直言非常强大(优点可能是有道理的。

剩下的就是品味问题了。