错误 C2678:二进制'!=':找不到采用左操作数的运算符
error C2678: binary '!=' : no operator found which takes a left-hand operand
template<typename T> T SmartIO::Peek() {
T temp;
T tempReturn;
while(true){
temp = *(T*)&buffer[ptrSeek];
if(temp !=0){
ptrSeek++;
tempReturn += *(T*)&buffer[ptrSeek];
}
else{
break;
}
}
return tempReturn;
}
所以我想做的是,从 ptrSeek 开始循环读取,将值添加到 temp 并检查 temp 的值 !=0 是否将此值添加到 tempReturn,一旦 temp 的值为 0,就中断循环并返回 tempReturn但是,但它一直给我这个错误:
error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)
我该如何在这里解决这个问题?
如果您尝试将任意类型T
与数字常量 0 进行比较,则模板代码存在一个基本问题,您在此处的代码中执行此操作:
T temp;
/* ... */
if(temp != 0){
/* ... */
}
这里的问题是T
是任意类型(在这种情况下,您似乎正在使用 std::string
实例化模板(,但您希望该类型与 0 相当。 这很好 - 它只是将T
限制为可以与 0 进行比较的类型 - 但从您将其报告为错误的事实来看,我不确定您是否知道这一点。
您的选择是不使用 std::string
作为参数来实例化此模板(它的编写方式,我认为您不应该能够这样做,因为看起来该函数不断将某种类型的值相加(,或者调试模板并更改其行为。 我不太确定您希望代码做什么,因此在后一种情况下,我不确定如何提供帮助。
希望这能澄清事情!
您可以专门化或重载比较部分(此处!=
(用于不能直接与0
比较的类型。举个例子,
template<typename T>
bool NotEqualto0 (const T& obj) { return (obj != 0); }
// overload for std::string
bool NotEqualto0 (const std::string &s) { return (s.c_str() != 0); }
...
if(NotEqualto0(temp))
...
[以上函数是硬连线的0
;它可以根据需要进行推广。
相关文章:
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 是否所有C++运算符都接受操作数?
- 一元*运算符的操作数是否期望一个 prvalue
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 没有运算符"="与这些操作数匹配,JUCE 窗口演示应用程序
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- CPP 运算符重载操作数位置 [] 与 ==
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- 错误 C2679 二进制"<<":未找到采用类型为 'T' 的右侧操作数的运算符
- 是否允许三元运算符在C++中计算两个操作数?
- 二进制 '==':未找到采用 'Enemy' 类型左侧操作数的运算符(或者没有可接受的转换)
- 与"运算符>>"不匹配(操作数类型为"QDataStream"和"QJsonObject")
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 如何摆脱逗号运算符的这个错误右操作数没有效果( wunsued 值)?
- c++ 错误:二进制"运算符+"类型"矩阵*"和"矩阵*"的操作数无效
- c++运算符重载-我实际返回的操作数类型是什么
- 没有运算符>>与这些操作数匹配 ifstream