简体   繁体   English

编译器告诉我 `unordered_map` 中的键类型不匹配 operator==

[英]The compiler tells me that there is no match for operator== for the key types in the `unordered_map`

In the following program the compiler seems to be missing the operator== for the keys in the unordered map.在下面的程序中,编译器似乎缺少用于无序映射中键的运算符==。 The way I understand it is that std::variant automatically delegates == to it's fields (if the same index is set and false otherwise).我的理解是std::variant自动将==委托给它的字段(如果设置了相同的索引,否则为false )。 Furthermore, I have a definition of operator== in the types A and B .此外,我在类型AB中定义了operator==

#include <variant>
#include <string>
#include <unordered_map>


struct Base {
public:
    virtual std::size_t get_hash() const = 0;
};

struct A : public Base {
    std::string s;
public:

    A(std::string str): s{str} {} 

    std::size_t get_hash() const override {
        return std::hash<std::string>{}(this->s);
    }

    bool operator==(const A a) {
        return a.s == this->s;
    }
};

struct B : public Base {
    int i;

public:
    B(int it): i{it} {}

    std::size_t get_hash() const override {
        return std::hash<int>{}(this->i);
    }

    bool operator==(const B b) {
        return b.i == this->i;
    }
};

namespace std {
    template<>
    struct hash<A> {
        size_t operator()(const A& a) const {
            return a.get_hash();
        }
    };

    template<>
    struct hash<B> {
        size_t operator()(const B& b) const {
            return b.get_hash();
        }
    };
}

int main(int argc, char* argv[]) 
{
    std::unordered_map<std::variant<A,B>, int> map;

    std::variant<A,B> key1{A("hi")};
    std::variant<A,B> key2{B(1)};

    map.insert({key1, 1});
    map.insert({key2, 2});
}    

Hence, I do not understand why the compiler complains about a lack of equality operator.因此,我不明白为什么编译器会抱怨缺少相等运算符。

The operator== need to be const , operator==需要是const

also it's better to take a const T& instead of const T也最好采用const T&而不是const T

struct A{
    // ...
    bool operator==(const A& a) const {
        return a.s == this->s;
    }
};
struct B{
    // ...
    bool operator==(const B& b) const {
        return b.i == this->i;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM