我的标准是
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
错误。但是,我已经包含了 string
,我没有明显的方法来解释这一点。
这是我的代码。
#include <string>
#include <vector>
#include <type_traits>
// [...]
template <typename T>
class Graph {
private:
// [...]
struct Vertex {
T name;
// [...]
};
std::vector<Vertex> verts;
public:
// [...]
template <typename P>
int vertex(P item) {
if (std::is_same<P,T>::value) {
for (unsigned int i = 0; i < verts.size(); i++){
if (verts[i].name == item) {
return i;
}
}
} else if (std::is_same<P,int>::value) {
return item;
}
return -1;
}
}
编译器为VS2012,平台为Windows 8.1 64bit。
最佳答案
做出有根据的猜测,在 if (verts[i].name == item)
似乎verts[i].name
已被实例化为 std::string
同时item
尚未实例化为 std::string
.因此,编译器合理地提示没有重载运算符来比较 std::string
。反对X
.
更新:
另一个猜测是 X
正在被实例化为 int
或 double
因为如果它被实例化为 std::string
编译器会提示尝试转换 std::string
到int
在 Graph::vertex()
中归还成员函数。
关于c++ - 无法解释的无法在模板中比较 C++ 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717362/