【问题标题】:Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'T'错误 C2679 二进制“<<”:未找到采用“T”类型右侧操作数的运算符
【发布时间】: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&lt;&lt; 函数以及你想放在这里的任何类型
  • fstream是从ostream派生出来的,正常的做法是为ostream编写函数,然后在其他流上下文中使用
  • int 版本已经存在,您的错误是由于其他一些自定义类型。错误消息应指定。或者你可能还没有完成#include &lt;fstream&gt;
  • 如果您仍有问题,请发帖stackoverflow.com/help/minimal-reproducible-example
  • 请务必检查编译器在实际错误之前或之后打印的信息性消息,这可能会提供更重要的细节。

标签: c++ templates visual-c++ compiler-errors fstream


【解决方案1】:

我的错,其中一个调用是“类枚举”。当然,>> 和

【讨论】:

    【解决方案2】:

    对于@cdhowie,这里有两个简单的示例(借助 load_and_save_data 模板方法):

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

    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中只写一次,具有简单的优点,并且具有相应的加载和保存代码(类型,顺序。 ..)。

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

    剩下的就是口味问题了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多