【发布时间】:2023-04-05 06:50:01
【问题描述】:
我正在尝试比较两个 std::map,但编译器拒绝它,因为它找不到 (==) 运算符。
1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\utility(275): error C2678: binary '==': no operator found which takes a left-hand operand of type 'const foo::Value' (or there is no acceptable conversion)
下面是一个例子。
namespace foo {
struct Key { int k; };
struct Value { int val; };
typedef std::map<Key*,Value> Map;
}
bool operator==(const foo::Value &v1, const foo::Value &v2)
{
return v1.val == v2.val;
}
bool operator!=(const foo::Value &v1, const foo::Value &v2)
{
return !(v1 == v2);
}
bool compare(foo::Map &to, const foo::Map &from)
{
return to != from;
}
如果我去掉命名空间,它就可以工作。
如果将 == 运算符定义为成员,则它可以工作。
例如:
struct Value {
int val;
bool operator==(const Value &v) const { return val == v.val; }
bool operator!=(const Value &v) const { return val != v.val; }
};
// elide the other == and !=
我做错了什么?就我而言,我希望 (==) 函数位于编译单元的本地而不是接口中。
【问题讨论】:
-
为什么你的键是指针?
-
这是有意的(我正在映射指针)。
-
“(我正在映射指针” - 我可以看到,我问“为什么”?
-
这是一种将信息与一些现有对象相关联的分析算法。我不明白为什么这是对关联容器的奇怪使用。有没有更好的方法(不修改
Value)? -
我问是因为行为可能也不完全符合您的预期 - 例如,请参阅 stackoverflow.com/questions/4607418/…。另外,如果您从地图中删除某些内容,键指向的内容会发生什么情况?