使用 std::equal
时出现编译错误(“不匹配运算符==”)并且我的类在单独的命名空间中定义(定义了适当的运算符)。
这是我使用 std::equal
的工作示例但没有命名空间,还有 没有编译错误
#include <vector>
#include <algorithm>
struct K {
int a;
};
struct V {
int b;
};
inline bool operator== (const K& lhs, const V& rhs) {
return lhs.a == rhs.b;
}
inline bool operator== (
const std::vector<K>& lhs, const std::vector<V>& rhs) {
return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
但是当我为我的类使用命名空间时,有“无匹配运算符”错误 #include <vector>
#include <algorithm>
namespace nk {
struct K {
int a;
};
}
namespace nv {
struct V {
int b;
};
}
inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
return lhs.a == rhs.b;
}
inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/bits/stl_algobase.h:1107:22: error: no match for 'operator==' (operand types are 'const nk::K' and 'const nv::V')
还有没有错误当
std::equal
替换为简单循环(比较运算符在这种情况下效果很好):inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
for(std::size_t i=0; i<lhs.size(); i++) {
if (!(lhs[i]==rhs[i])) {
return false;
}
}
return true;
}
代码已使用 Compiler Explorer 和 GCC 10.0.2 进行测试(我还测试了其他 GCC 版本)
最佳答案
问题是图书馆喜欢 std::equal
找不到 operator==
在全局范围内定义。
您可以移动operator==
进入命名空间 where K
或 V
定义为验证 ADL . (PS 你的第一个代码片段也因为 ADL 起作用。)
例如。
namespace nk {
struct K {
int a;
};
}
namespace nv {
struct V {
int b;
};
inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
return lhs.a == rhs.b;
}
}
LIVE
关于c++ - 使用 std::equal 和命名空间时出现 "No match operator=="错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66999617/