c++ - 未找到重载函数

标签 c++ namespaces operator-overloading type-alias

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

相关文章:

c++ - 如何测试引用是否为 NULL?

c++ - 使用运算符 == 的结构重载

c++ - 使用operator=和initializer_list找不到继承

c++ - 如何使用visual studio c++与ZIGBEE传输数据

c++ - 为什么 C++ 可执行文件在与较新的 libstdc++.so 链接时运行速度如此之快?

c++ - MSVC 2013 'type': 不是 'std::enable_if<false,void> 的成员

c# - 使用结构 union 将 C++ 编码到 C# 结构

php - 使用 PHP 为 XML 标记设置命名空间

Java+DOM : How do I set the base namespace of an (already created) Document?

c# - 在决定是否创建另一个 Visual Studio 项目 (.NET) 时应使用什么标准?