gpt4 book ai didi

c++ - 未找到重载函数

转载 作者:行者123 更新时间:2023-12-04 16:59:37 24 4
gpt4 key购买 nike

我有课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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com