c++ - 未找到重载函数
问题描述
我有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>;
};
如果需要,您可以将其他比较功能留在那里。我删除了它,因为看起来你只是为地图定义了它。
推荐阅读
- python - 我想在 GEKKO 数据的非线性回归中的给定点施加值和斜率约束,请帮助我
- javascript - 找不到模块 - 反应
- javascript - 如何在 Javascript 中仅设置 onClick 间隔?
- python - 解密密码学 fernet 编码以检查输入是否相同
- python - FastAPI + Jinja2 Web App 的 DRY 原则(前后端)
- datepicker - 没有年份的日期选择器
- react-testing-library - 如何使用 React 测试库“按元素查找”
- php - PHP - session_write_close() - 跨页面传递 $_SESSION 变量
- python - 如何从 PDF 中提取某些信息并将其附加到 python 中的 excel 电子表格中?
- python - 将值从一个字典复制到另一个字典的最pythonic方法是什么?