【发布时间】:2015-12-16 17:01:19
【问题描述】:
我不知道如何使用std::reference_wrapper 将std::string 引用引用到std::unordered_map。根据以下链接,我知道我需要重载operator==。
Why can template instances not be deduced in `std::reference_wrapper`s?
但是,我不知道如何编写 operator== 以使其需要 const std::reference_wrapper。如果 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; }
【问题讨论】:
标签: c++ c++11 stl operator-overloading reference-wrapper