首页 > 解决方案 > 未找到重载函数

问题描述

我有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)?

标签: c++namespacesoperator-overloadingtype-alias

解决方案


一个简单的选择是定义您自己的比较器并将其提供给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>;
};

如果需要,您可以将其他比较功能留在那里。我删除了它,因为看起来你只是为地图定义了它。


推荐阅读