我有课KeyA
那是来自第三方的,将是使用中的关键。当我定义“<”运算符时,它会提示:
error: no match for ‘operator<’ (operand types are ‘const KeyA’ and ‘const KeyA’)
一些简化的代码来显示问题:#include <map>
using namespace std;
struct KeyA { // defined in somewhere else
int a;
};
namespace NS {
struct config {
using Key = KeyA; // type alias
using Table = map<Key, int>;
};
bool operator <(const config::Key& lhs, const config::Key& rhs) {
return lhs.a <rhs.a ;
}
}
int main()
{
using namespace NS;
config::Table table;
table[{1}]= 2;
return 0;
}
这里会发生什么?以及如何解决这个问题(无法触及 KeyA
并且很可能必须将重载的函数保留在 NS
中)?
最佳答案
一个简单的选择是定义您自己的比较器并将其提供给 std::map
模板参数代替:
struct config
{
using Key = KeyA; // type alias
struct KeyLess {
bool operator ()(const Key& lhs, const Key& rhs) const {
return lhs.a < rhs.a;
}
};
using Table = map<Key, int, KeyLess>;
};
如果需要,您可以将其他比较功能留在那里。我删除了它,因为看起来你只是为 map 定义了它。
关于c++ - 未找到重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69826919/