4

我不知道如何std::string使用. 根据以下链接,我了解我需要重载。std::unordered_mapstd::reference_wrapperoperator==

为什么 `std::reference_wrapper`s 中不能推导出模板实例?

但是,我不知道如何编写operator==它需要一个const std::reference_wrapper。如果包装器不是const则不会有问题。

使用 char 而不是std::string工作正常(不需要重载operator==)。

代码:

#include <iostream>
#include <unordered_map>
#include <functional>

bool operator==(const std::reference_wrapper<std::string> lhs,
                const std::reference_wrapper<std::string> rhs)
{
    return std::equal_to<std::string>()(lhs.get(), rhs.get());
}

int main(){
    char        chr('a');
    std::string str("b");
    int         num(1);

    // this works (char)
    std::unordered_map<std::reference_wrapper<char>, int, std::hash<char>> charMap;
    std::pair<std::reference_wrapper<char>, int> charPair(chr , num);
    charMap.insert(charPair);
    std::cout << "charMap works.  Output: " << charMap[chr] << std::endl;

    // does not work (std::string)
    std::unordered_map<std::reference_wrapper<std::string>, int, std::hash<std::string>> stringMap;
    std::pair<std::reference_wrapper<std::string>, int> stringPair(str , num);
    stringMap.insert(stringPair);  // compile error
}

编译错误:

error: no match for ‘operator==’ (operand types are ‘const std::reference_wrapper<std::__cxx11::basic_string<char> >’ and ‘const std::reference_wrapper<std::__cxx11::basic_string<char> >’)
       { return __x == __y; }
4

1 回答 1

11

operator==您不能为非用户定义的类型提供自己的重载。也就是说,充其量是未定义的行为。但是,您不需要在此处执行此操作。std::unordered_map五个模板参数:

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;

看到第四张了吗?那就是你想要的。您需要提供一个函数进行比较。幸运的是,您可以像这样使用 std::hash 和 std::equal_to :

std::unordered_map<
    std::reference_wrapper<std::string>,
    int,
    std::hash<std::string>,
    std::equal_to<std::string>
> stringMap;
于 2015-09-19T17:15:41.223 回答