我在使用C++标准库时遇到了麻烦。以下示例无法编译:(请注意,这是为了制作最小示例而削减的,因此它本身并没有太多意义)
#include <algorithm>
#include <string>
#include <vector>
namespace otherns {
class Property {
public:
const std::string &getName() const { return m_name; }
private:
std::string m_name;
};
}
bool operator==(const otherns::Property &a, const otherns::Property &b) {
return a.getName() == b.getName();
}
/* Merge, second takes priority */
std::vector<otherns::Property>
merge_props(const std::vector<otherns::Property> &xs,
const std::vector<otherns::Property> &ys) {
std::vector<otherns::Property> ans = ys;
for (const auto &x : xs) {
if (std::find(ans.begin(), ans.end(), x) == ans.end()) {
ans.push_back(x);
}
}
return ans;
}
错误是“二进制'==':没有找到接受左操作数类型为'otherns :: Property'的运算符(或没有可接受的转换)”,它出现在
std :: find 的实现中的某个位置。这是使用MSVC发生的,但我也尝试过clang和gcc,并获得了类似的结果。
以下代码可以正常工作:
std::vector<otherns::Property>
merge_props(const std::vector<otherns::Property> &xs,
const std::vector<otherns::Property> &ys) {
std::vector<otherns::Property> ans = ys;
for (const auto &x : xs) {
if (std::find_if(ans.begin(), ans.end(), [&x](const otherns::Property &y) {
return x == y;
}) == ans.end()) {
ans.push_back(x);
}
}
return ans;
}
我猜这似乎与ADL / Koenig查找有关,但我真的不明白为什么我的operator==
没有找到。如果我想使用第一个更简单的find
函数形式,最好的解决方案是什么?
实际上,otherns
来自于第三方库的头文件,所以我不能将我的运算符放入该头文件中。
operator==
没有实现所谓的相等性(实际类Property
有比名称更多的数据成员),所以我所做的有点欺骗/黑客行为。我认为不应该修改库。 - Peter Hull