Overload operator == for const std :: reference_wrapper in std :: unordered_map

I can’t figure out how to get the link std::stringin std::unordered_mapusing std::reference_wrapper. By the following link, I understand that I need to reload operator==.

Why can't template instances be displayed in `std :: reference_wrapper`?

However, I cannot figure out how to write operator==it to accept const std::reference_wrapper . If the shell was not const , this was not a problem.

Using char instead std::stringworks fine (no overload required operator==).

code:

#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
}

Compilation 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
source share
1 answer

operator== - . , , undefined. . 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;
+6

Source: https://habr.com/ru/post/1608153/


All Articles